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