`

Java 异常处理机制

阅读更多


 1.异常的分类



 

 

 

The Error hierarchy describes internal errors and resource exhaustion inside the Java runtime system. You should not throw an object of this type. There is little you can do if such an internal error occurs, beyond notifying the user and trying to terminate the program gracefully. These situations are quite rare.

 

When doing Java programming, you focus on the Exception hierarchy. The Exception hierarchy also splits into two branches: exceptions that derive from RuntimeException and those that do not. The general rule is this: A RuntimeException happens because you made a programming error. Any other exception occurs because a bad thing, such as an I/O error, happened to your otherwise good program.

Exceptions that inherit from RuntimeException include such problems as

  • A bad cast;

  • An out-of-bounds array access;

  • A null pointer access.

Exceptions that do not inherit from RuntimeException include

  • Trying to read past the end of a file;

  • Trying to open a malformed URL;

  • Trying to find a Class object for a string that does not denote an existing class.

The Java Language Specification calls any exception that derives from the class Error or the class RuntimeException an unchecked exception. All other exceptions are called checked exceptions. This is useful terminology that we also adopt. The compiler checks that you provide exception handlers for all checked exceptions.

 

unchecked exception: Error /RuntimeException

checked exceptions: All other exceptions  必须进行处理

 

2.声明异常 Declaring Checked Exceptions

 

  • You call a method that throws a checked exception, for example, the FileInputStream constructor. 已检查异常一定要进行处理
  • You detect an error and throw a checked exception with the throw statement (we cover the tHRow statement in the next section).
  • You make a programming error, such as a[-1] = 0 that gives rise to an unchecked exception such as an ArrayIndexOutOfBoundsException.
  • An internal error occurs in the virtual machine or runtime library.

 

In summary, a method must declare all the checked exceptions that it might throw. Unchecked exceptions are either beyond your control (Error) or result from conditions that you should not have allowed in the first place (RuntimeException). If your method fails to faithfully declare all checked exceptions, the compiler will issue an error message.

必须声明已检查异常,不然编译器通不过 

 

If you override a method from a superclass, the checked exceptions that the subclass method declares cannot be more general than those of the superclass method. (It is Ok to throw more specific exceptions, or not to throw any exceptions in the subclass method.) In particular, if the superclass method throws no checked exception at all, neither can the subclass. For example, if you override JComponent.paintComponent, your paintComponent method must not throw any checked exceptions, because the superclass method doesn't throw any.

 

子类方法中抛出的异常范围更加小或者根本不抛出异常。

 

When a method in a class declares that it throws an exception that is an instance of a particular class, then it may throw an exception of that class or of any of its subclasses. For example, the FileInputStream constructor could have declared that it throws an IOException. In that case, you would not have known what kind of IOException. It could be a plain IOException or an object of one of the various subclasses, such as FileNotFoundException.

也就是异常类的多态性。

 

3.Throw an Exception 抛出异常

 

 

Once a method throws an exception, the method does not return to its caller. This means that you do not have to worry about cooking up a default return value or an error code.

 

一个方法中,抛出异常后就退出该方法了,不再返回到方法的调用者了。不return。。。。

 

 

4.Creating Exception Classes 创建自定义异常(extends Exception)

  

二、Catching Exceptions(捕获异常)

 

1.

try
{

   code
   more code
   more code
}
catch (ExceptionType e)
{
   handler for this type
}

 

2. best way

 

   public void read(String filename)
{

   TRy
   {
      InputStream in = new FileInputStream(filename);
      int b;
      while ((b = in.read()) !=-1)
      {
         process input
      }
   }
   catch (IOException exception)
   {
      exception.printStackTrace();
   }
}

  

 
 

Remember, the compiler strictly enforces the throws specifiers. If you call a method that throws a checked exception, you must either handle it or pass it on.

调用一个抛出已检查异常的方法,必须处理或者再次将此异常抛出去

当知道如何去处理一个异常就catch,不然就throw....

 

 

Please keep in mind that there is one exception to this rule, as we mentioned earlier. If you are writing a method that overrides a superclass method that throws no exceptions (such as paintComponent in JComponent), then you must catch each checked exception in the method's code. You are not allowed to add more throws specifiers to a subclass method than are present in the superclass method.

 

 

 

  

Often, the best choice is to do nothing at all and simply pass the exception on to the caller. If an error occurs in the read method, let the caller of the read method worry about it! If we take that approach, then we have to advertise the fact that the method may throw an IOException.

 

最好还是直接将异常抛出,由调用者来处理
public void read(String filename) throws IOException
{
   InputStream in = new FileInputStream(filename);
   int b;
   while ((b = in.read()) !=-1)
   {
      process input
   }
}

If any of the code inside the try block throws an exception of the class specified in the catch clause, then

 

  • The program skips the remainder of the code in the try block;   不执行抛出异常点后的操作转而去执行catch中的操作,try中没有抛出异常,catch将不会执行。
  • The program executes the handler code inside the catch clause. 
  • try中抛出的异常并不是catch中的异常,则this method exits immediately

  

3.Rethrowing and Chaining Exceptions

 

  可以在catche中再次将异常抛出,这样可以改变异常的类型。

 

  try
{

   access the database
}
catch (SQLException e)
{
   THRowable se = new ServletException("database error");
   se.setCause(e);
   tHRow se;
}  

 

When the exception is caught, the original exception can be retrieved:

  Throwable e = se.getCause();
 这种做法很好,它能够抛出子系统中的高级异常,但不会丢失原始异常的细节。 这种包装技术可以将已检查异常(checked exception)包装成运行时异常(runtime exception ,unchecked exception)

 (这点还需要好好好好理解!)

 

 

4.The finally Clause

  

  异常处理中,程序的执行情况:

 

  Graphics g = image.getGraphics();
TRy

{
   // 1
   code that might throw exceptions
   // 2
}
catch (IOException e)
{
   // 3
   show error dialog
   // 4
}
finally
{
   // 5
   g.dispose();
}
// 6

  look at the three possible situations in which the program will execute the finally clause.

  • The code throws no exceptions. In this event, the program first executes all the code in the TRy block. Then, it executes the code in the finally clause. Afterwards, execution continues with the first statement after the try block. In other words, execution passes through points 1, 2, 5, and 6.
    没有抛出异常时,程序的走向 1,2,5,6
  • The code throws an exception that is caught in a catch clause, in our case, an IOException. For this, the program executes all code in the try block, up to the point at which the exception was thrown. The remaining code in the try block is skipped. The program then executes the code in the matching catch clause, then the code in the finally clause.
    抛出了catch中可以捕获的异常
    If the catch clause does not throw an exception, then the program executes the first line after the try block. In this scenario, execution passes through points 1, 3, 4, 5, and 6.
    抛出了catch中可以捕获的异常,并且catche中没有抛出异常,程序的走向1,3,4,5,6

    If the catch clause throws an exception, then the exception is thrown back to the caller of this method, and execution passes through points 1, 3, and 5 only.
    抛出了catch中可以捕获的异常,但是catche中也抛出了异常,程序的走向1,3,5,程序跳出到调用者
  • The code throws an exception that is not caught in any catch clause. For this, the program executes all code in the try block until the exception is thrown. The remaining code in the try block is skipped. Then, the code in the finally clause is executed, and the exception is thrown back to the caller of this method. Execution passes through points 1 and 5 only.
    抛出了异常,但是并不是catche中可以捕获的异常类型,程序走向1,5

 5.Tips for Using Exceptions

    1.Exception handling is not supposed to replace a simple test.捕获异常更耗时

    2.Do not micromanage exceptions. 不要过分的细代异常

    3.Do not squelch exceptions.

    4.Propagating exceptions is not a sign of shame. Often, it is actually better to propagate the exception instead of catching it:

 

 

 

 

 

 

  • 大小: 27.4 KB
分享到:
评论

相关推荐

    浅析JAVA异常处理机制.pdf

    ### 浅析JAVA异常处理机制 #### 一、Java异常处理机制概述 异常处理是Java语言中的一个重要机制,它能够确保程序在遇到不可预料的情况时仍能维持稳定运行。异常处理主要包括三个方面:捕获异常、控制程序流程以及...

    14.java异常处理机制.zip

    14.java异常处理机制.zip14.java异常处理机制.zip14.java异常处理机制.zip14.java异常处理机制.zip14.java异常处理机制.zip14.java异常处理机制.zip14.java异常处理机制.zip14.java异常处理机制.zip14.java异常处理...

    深入理解java异常处理机制

    ### 深入理解Java异常处理机制 #### 引言 异常处理机制是任何现代编程语言不可或缺的一部分,尤其是在像Java这样的面向对象的语言中更是如此。Java的异常处理机制旨在帮助开发者编写更健壮、更易于维护的代码。...

    java异常处理机制

    java异常处理机制,异常的概念,发生的原因,throwable,捕获异常的简单思维导图

    Java异常处理机制及应用.pdf

    Java 异常处理机制及应用 Java 异常处理机制是一种重要的技术,它能够帮助开发者处理 Java 语言中的错误和异常,从而提高程序的可靠性和稳定性。本文将从 Java 异常处理机制的原理、分类、抛出和捕获机制、原则等...

    Java异常处理机制及应用研究.pdf

    Java 异常处理机制及应用研究 Java 异常处理机制是 Java 程序设计的一大难点,也是使用 Java 进行软件开发时不容忽视的问题之一。是否进行异常处理直接关系到开发出的软件的稳定性和健壮性。对 Java 异常处理机制有...

    Java异常处理机制及其在项目中的应用.pdf

    Java 异常处理机制及其在项目中的应用 Java 异常处理机制是 Java 语言中的一种错误捕获机制,用于处理程序中的错误和异常。Java 异常处理机制可以分为两大类:Checked Exception 和 Unchecked Exception。Checked ...

    基于Java异常处理机制的分析.pdf

    "基于Java异常处理机制的分析" 本文主要讨论了Java异常处理机制的原理和应用。Java是一种面向对象的编程语言,对异常处理的支持非常出色。Java通过类来封装异常,并使用“try/ catch/finally”机制来处理异常,最后...

    Java异常处理机制应用研究.pdf

    "Java 异常处理机制应用研究" Java 异常处理机制是 Java 程序设计中的一个重要方面,正确使用异常处理的策略和方法,能够确保 Java 程序结构的清晰性、易读性和健壮性。本文将详细介绍 Java 异常处理机制的应用研究...

    高效java异常处理机制

    通过遵循上述最佳实践,开发者可以编写出更健壮、可维护的Java代码,有效地利用Java异常处理机制来提高程序的稳定性。同时,阅读并理解"Effective Java Exceptions"文档可以帮助进一步深化对Java异常处理的理解。

    深入理解java异常处理机制Java开发Java经验技巧共

    Java异常处理机制是Java编程中不可或缺的一部分,它提供了一种有序地处理程序错误和异常情况的方法。这篇19页的PDF文档《深入理解java异常处理机制Java开发Java经验技巧共》可能涵盖了Java异常处理的基本概念、最佳...

    java异常处理机制示例(java抛出异常、捕获、断言)

    Java异常处理机制是Java编程中不可或缺的一部分,它用于处理程序运行过程中可能出现的错误或异常情况。这个机制通过五个关键字:try、catch、throw、throws、finally来实现。 1. **try** 关键字:用于包围可能抛出...

    JAVA异常处理机制——经验与技巧.pdf

    JAVA 异常处理机制——经验与技巧 本文旨在探讨 JAVA 中的异常处理机制,旨在帮助开发者更好地理解和掌握 JAVA 异常处理机制,提高程序的安全性和可用性。 一、什么是异常? 在 JAVA 中,异常是程序在运行期发生...

    Java异常处理机制的静态编译实现与优化

    异常处理机制是面向对象语言普遍支持的提高软件可靠性的方法。作为两款被广泛使用的面向对象语言,C++和Java语言都支持异常处理机制...该算法可以同时支持C++和Java异常处理机制,并有效提高了抛出异常较多的程序的性能。

    论文研究-基于Java异常处理机制的研究 .pdf

    Java异常处理机制研究的知识点涵盖了异常处理的基本概念、分类、原则以及实际应用等方面。 1. 异常处理概念 异常处理是Java语言中用于处理程序运行时遇到的错误和异常情况的一种机制。它通过异常类的层次结构来实现...

    浅析Java异常处理机制.pdf

    浅析Java异常处理机制 在 Java 编程中,异常处理机制是非常重要的一部分。任何一种程序设计语言编写的程序,在运行期间都有可能会出现一个不可能执行的操作,该操作的结果会导致程序运行错误。我们可以使用异常处理...

    关于Java异常处理机制的深入理解.doc

    Java异常处理机制是Java编程中一个至关重要的概念,它提供了对程序运行时错误的优雅处理方式。在Java中,异常是程序执行过程中发生的错误,这些错误可能会中断正常的流程。异常处理通过`try-catch-finally`块来实现...

    Java编程语言入门 Java语言基础教程 第08课 Java异常处理机制Exception 共21页.pdf

    ### Java异常处理机制详解 #### 一、Java异常处理概览 Java的异常处理机制是一种用于处理程序运行过程中出现的异常情况的有效手段。相比于传统的错误处理方式(如C语言中的返回值检查),Java的异常处理提供了更为...

Global site tag (gtag.js) - Google Analytics