1、如果在函數內拋出該異常,在函數上可以不用聲明
class OwnException extends RuntimeException{
OwnException(String msg){
super(msg);
}
}
class RuntimeExceptionTest{
public int show(int a,int b){
if(b == 0)
throw new OwnException("除數不能爲零");
return a/b;
}
}
public class RuntimeExceptionDemo {
public static void main(String[] args) {
RuntimeExceptionTest runtimeExceptionTest = new RuntimeExceptionTest();
int num = runtimeExceptionTest.show(5, 0);
System.out.println("num="+num);
}
}
2、如果在函數上聲明,在調用此函數着可以不進行處理
class OwnException extends RuntimeException{
OwnException(String msg){
super(msg);
}
}
class RuntimeExceptionTest{
public int show(int a,int b)throws OwnException{
return a/b;
}
}
public class RuntimeExceptionDemo {
public static void main(String[] args) {
RuntimeExceptionTest runtimeExceptionTest = new RuntimeExceptionTest();
int num = runtimeExceptionTest.show(5, 0);
System.out.println("num="+num);
}
}