throws表示当前方法不处理异常,而是交给方法的调用出去处理;
throw表示直接抛出一个异常;
1public class Demo1 { 2 3 /** 4 * 把异常向外面抛 5 * @throws NumberFormatException 6 */ 7 public static void testThrows()throws NumberFormatException{ 8 String str="123a"; 9 int a=Integer.parseInt(str); 10 System.out.println(a); 11 } 12 13 public static void main(String[] args) { 14 try{ 15 testThrows(); 16 System.out.println("here"); 17 }catch(Exception e){ 18 System.out.println("我们在这里处理异常"); 19 e.printStackTrace(); 20 } 21 System.out.println("I'm here"); 22 } 23}
这里我们直接把异常抛出了。
运行输出:
1我们在这里处理异常 2java.lang.NumberFormatException: For input string: "123a" 3 at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 4 at java.lang.Integer.parseInt(Integer.java:580) 5 at java.lang.Integer.parseInt(Integer.java:615) 6 at com.java1234.chap04.sec03.Demo1.testThrows(Demo1.java:11) 7 at com.java1234.chap04.sec03.Demo1.main(Demo1.java:17) 8I'm here
throw表示直接抛出一个异常;
我们可以根据业务在代码任何地方抛出异常:
1package com.java1234.chap04.sec03; 2 3public class Demo2 { 4 5 public static void testThrow(int a) throws Exception{ 6 if(a==1){ 7 // 直接抛出一个异常类 8 throw new Exception("有异常"); 9 } 10 System.out.println(a); 11 } 12 13 public static void main(String[] args) { 14 try { 15 testThrow(1); 16 } catch (Exception e) { 17 // TODO Auto-generated catch block 18 e.printStackTrace(); 19 } 20 } 21}
运行输出:
1java.lang.Exception: 有异常 2 at com.java1234.chap04.sec03.Demo2.testThrow(Demo2.java:8) 3 at com.java1234.chap04.sec03.Demo2.main(Demo2.java:15)