Java基礎-throw和throws


雖然了解一些有關 Java 的異常處理,但是發現自己對 throw 和 throws 二者還不是很清楚,所以想深入的理解理解。

拋出異常的三種方式

系統自動拋出異常、throw 和 throws三種方式。

1、系統自動拋出異常

public class ThrowTest {
	
	public static void main(String[] args) {
		int a = 0;
		int b = 1;
		System.out.println(b / a);
	}

}

運行該程序后系統會自動拋出 ArithmeticException 算術異常。

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at com.sywf.study.ThrowTest.main(ThrowTest.java:8)

2、throw
throw 指的是語句拋出異常,后面跟的是對象,如:throw new Exception,一般用於主動拋出某種特定的異常,如:

public class ThrowTest {
	
	public static void main(String[] args) {
		String string = "abc";
		if ("abc".equals(string)) {
			throw new NumberFormatException();
		} else {
			System.out.println(string);
		}
	}

}

運行后拋出指定的 NumberFormatException 異常。

Exception in thread "main" java.lang.NumberFormatException
	at com.sywf.study.ThrowTest.main(ThrowTest.java:8)

3、throws
throws 用於方法名后,聲明方法可能拋出的異常,然后交給調用其方法的程序處理,如:

public class ThrowTest {

	public static void test() throws ArithmeticException {
		int a = 0;
		int b = 1;
		System.out.println(b / a);
	}

	public static void main(String[] args) {
		try {
			test();
		} catch (ArithmeticException e) {
			// TODO: handle exception
			System.out.println("test() -- 算術異常!");
		}
	}

}

程序執行結果:

test() -- 算術異常!

throw 與 throws 比較

1、throw 出現在方法體內部,而 throws 出現方法名后。
2、throw 表示拋出了異常,執行 throw 則一定拋出了某種特定異常,而 throws 表示方法執行可能會拋出異常,但方法執行並不一定發生異常。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM