throws關鍵字通常被應用在聲明方法時,用來指定可能拋出的異常,多個異常可以使用逗號隔開。僅當拋出了checked 異常,該方法的調用者才必須處理或重新拋出該異常。如果main方法也拋出獲取的異常,最終JVM會進行處理,打印異常消息和堆棧信息。
throw關鍵字通常用在方法體中,並且拋出一個異常對象。程序在執行到throw語句時立即停止,它後面的語句(方法體中)都不執行。
舉例說明:
- public class Test {
- public static void main(String args[]) {
- try {
- test();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- static void test(){
- throw new Exception("test");
- }
- }
上面這段程序有問題,有兩種修改方案:
一、在test()方法前用throws關鍵字拋出異常
- public class Test {
- public static void main(String args[]) {
- try {
- test();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- static void test() throws Exception{
- throw new Exception("test");
- }
- }
二、用try/catch語句塊將throw new Exception("test");這句包圍
- public class Test {
- public static void main(String args[]) {
- try {
- test();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- static void test() {
- try {
- throw new Exception("test");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }