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:

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值