Java 異常語句

2018-02-20 01:10 更新

Java教程 - Java異常語句


為了防止和處理運行時錯誤,請將代碼包含在try塊中進(jìn)行監(jiān)視。

緊跟在try塊之后,包括一個catch子句它指定您希望捕獲的異常類型。

Java try catch語句

public class Main {
  public static void main(String args[]) {
    try { // monitor a block of code.
      int d = 0;
      int a = 42 / d;
      System.out.println("This will not be printed.");
    } catch (ArithmeticException e) { // catch divide-by-zero error
      System.out.println("Division by zero.");
    }
    System.out.println("After catch statement.");
  }
}

上面的代碼生成以下結(jié)果。


多個catch子句

您可以指定兩個或多個catch子句,每個捕獲不同類型的異常。

當(dāng)拋出異常時,將按順序檢查每個catch語句,并執(zhí)行類型與異常類型匹配的第一個。

在執(zhí)行一個catch語句之后,繞過其他catch語句,并在try/catch塊之后繼續(xù)執(zhí)行。

public class Main {
  public static void main(String args[]) {
    try {
      int a = args.length;
      System.out.println("a = " + a);
      int b = 42 / a;
      int c[] = { 1 };
      c[42] = 99;
    } catch (ArithmeticException e) {
      System.out.println("Divide by 0: " + e);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Array index oob: " + e);
    }
    System.out.println("After try/catch blocks.");
  }
}

當(dāng)您使用多個catch語句時,異常子類必須在它們的任何超類之前。

上面的代碼生成以下結(jié)果。


嵌套try語句

try語句可以嵌套。

public class Main {
  public static void main(String args[]) {
    try {
      int a = args.length;
      int b = 42 / a;
      System.out.println("a = " + a);
      try { // nested try block
        if (a == 1)
          a = a / (a - a); // division by zero exception
        if (a == 2) {
          int c[] = { 1 };
          c[4] = 9; // an out-of-bounds exception
        }
      } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Array index out-of-bounds: " + e);
      }
    } catch (ArithmeticException e) {
      System.out.println("Divide by 0: " + e);
    }
  }
}

上面的代碼生成以下結(jié)果。

Java throw語句

我們可以在異常情況下拋出異常。

語法

throw的一般形式如下所示:

 throw ThrowableInstance; 

這里,ThrowableInstance必須是Throwable類型的對象或Throwable的子類。

有兩種方法可以獲取Throwable對象:在catch子句中使用參數(shù),或者使用new運算符創(chuàng)建一個。

執(zhí)行流程在throw語句之后立即停止; 任何后續(xù)不執(zhí)行語句。

如何使用Java throws語句?

public class Main {
  static void aMethod() {
    try {
      throw new NullPointerException("demo");
    } catch (NullPointerException e) {
      System.out.println("Caught inside demoproc.");
      throw e; // rethrow the exception
    }
  }

  public static void main(String args[]) {
    try {
      aMethod();
    } catch (NullPointerException e) {
      System.out.println("Recaught: " + e);
    }
  }
}

上面的代碼生成以下結(jié)果。

Java throws語句

如果一個方法想拋出一個異常,它必須指定這個行為。

這是包含throws子句的方法聲明的一般形式:

type method-name(parameter-list) throws exception-list 
{ 
// body of method 
}

exception-list是一個逗號分隔的列表,列出了方法可以拋出的異常。

public class Main {
  static void throwOne() throws IllegalAccessException {
    System.out.println("Inside throwOne.");
    throw new IllegalAccessException("demo");
  }

  public static void main(String args[]) {
    try {
      throwOne();
    } catch (IllegalAccessException e) {
      System.out.println("Caught " + e);
    }
  }
}

上面的代碼生成以下結(jié)果。

Java finally語句

任何代碼,將被執(zhí)行,不管try塊放在一個 finally 阻止。

這是異常處理塊的一般形式:

try { 
// block of code to monitor for errors 
} 
catch (ExceptionType1 exOb) { 
// exception handler for ExceptionType1 
}
catch (ExceptionType2 exOb) { 
// exception handler for ExceptionType2 
}
// ... 
finally { 
// block of code to be executed after try block ends 
}

finally 創(chuàng)建一個代碼塊在 try/catch 塊完成后執(zhí)行。

即使沒有catch語句與異常匹配, finally 塊也將執(zhí)行。

finally 塊可用于關(guān)閉文件句柄和釋放任何其他資源。finally子句是可選的。

public class Main {
  // Through an exception out of the method.
  static void methodC() {
    try {
      System.out.println("inside methodC");
      throw new RuntimeException("demo");
    } finally {
      System.out.println("methodC finally");
    }
  }

  // Return from within a try block.
  static void methodB() {
    try {
      System.out.println("inside methodB");
      return;
    } finally {
      System.out.println("methodB finally");
    }
  }

  // Execute a try block normally.
  static void methodA() {
    try {
      System.out.println("inside methodA");
    } finally {
      System.out.println("methodA finally");
    }
  }

  public static void main(String args[]) {
    try {
      methodC();
    } catch (Exception e) {
      System.out.println("Exception caught");
    }
    methodB();
    methodA();
  }
}

上面的代碼生成以下結(jié)果。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號