目錄java
public static void main(String[] args) { // try { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = a / b; System.out.println("輸入的兩個數相除結果爲: " + c); } //IndexOutOfBoundsException catch(IndexOutOfBoundsException ie){ System.out.println("數組越界"); } //NumberFormatException catch(NumberFormatException ne){ System.out.println("數字格式異常"); } //ArithmeticException catch(ArithmeticException ae){ System.out.println("算術異常"); } catch (Exception e) { System.out.println("未知異常"); } }
Java7後提供一個catch捕獲多個異常
數組
public static void main(String[] args) { // try { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = a / b; System.out.println("輸入的兩個數相除結果爲: " + c); } //Multiple Exception catch(IndexOutOfBoundsException | NumberFormatException | ArithmeticException me){ System.out.println("多個異常"); } catch (Exception e) { System.out.println("未知異常"); } }
public static void main(String[] args) { // try { FileInputStream i = new FileInputStream("a.txt"); } //Multiple Exception catch(IOException ie){ System.out.println("exception message: " + ie.getMessage()); ie.printStackTrace(); } catch (Exception e) { System.out.println("未知異常"); } }
exception message: a.txt (系統找不到指定的文件。) java.io.FileNotFoundException: a.txt (系統找不到指定的文件。) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at com.company.project.exception.ExceptionPrint.main(ExceptionPrint.java:11)
package com.company.project.exception; import java.io.FileInputStream; import java.io.IOException; public class ExceptionPrint { public static void main(String[] args)throws IOException {//這裏拋出IOException //throw exception FileInputStream i = new FileInputStream("a.txt"); } //定義的新函數拋出指定的異常 public static void test() throws Exception {}; }
throw和throws區別:jvm
public class ExceptionPrint { /*throws & throw*/ public static void main(String[] args)throws IOException {//這裏拋出IOException FileInputStream i = new FileInputStream("a.txt"); } //定義的新函數拋出指定的異常 public static void test() throws Exception {}; public void DoSomething(){ int a = 1; int b = 2; if (a != b) { //能夠定義本身的異常 throwMyException(); //也能夠定義其餘的異常,根據須要使用 throw new IndexOutOfBoundsException(); } } public static void throwMyException(){ System.out.println("我本身定義的異常"); } }
package com.company.project.exception; //MyNewException。java public class MyNewException extends Exception { //無參構造 public MyNewException(){}; //有參構造 public MyNewException(String msg){ super(msg); } }
finnaly在有try語句塊的時候才能使用,在jvm不退出的狀況下必定會執行函數