background image

Java 开发:Java 语言中的两种异常

Java 提 供 了 两 类 主 要 的 异 常 :runtime exception 和 checked exception 。 所 有 的
checked exception 是从 java.lang.Exception 类衍生出来的,而 runtime exception
则是从 java.lang.RuntimeException 或 java.lang.Error 类衍生出来的。
  它们的不同之处表现在两方面:机制上和逻辑上。
  一、机制上
  它们在机制上的不同表现在两点:1.如何定义方法;2. 如何处理抛出的异常。请看下面
CheckedException 的定义:
  public class CheckedException extends Exception {
  public CheckedException() {}
  public CheckedException( String message ){
  super( message );
  }
  }
  以及一个使用 exception 的例子:
  public class ExceptionalClass{
  public void method1() throws CheckedException {
  // ... throw new CheckedException( “...

“ 

出错了 );

  }
  public void method2( String arg ) {
  if( arg == null )
  {
  throw new NullPointerException( “method2 的参数 arg 是 null!” );
  }
  }
  public void method3() throws CheckedException{
  method1();
  }

 

   }

  你可能已经注意到了,两个方法 method1()和 method2()都会抛出 exception,
可是只有 method1()做了声明。另外,method3()本身并不会抛出 exception,可是它
却声明会抛出 CheckedException。在向你解释之前,让我们先来看看这个类的 main()
方法:
  public static void main( String[] args )
  {
  ExceptionalClass example = new ExceptionalClass();
  try