继承Exception和继承RuntimeException有什么区别
继承Exception和继承RuntimeException有什么不同效果?
创建两个异常类
package anomyous;
public class TooSmallException extends RuntimeException{
public TooSmallException(String message,int num) {
super(message);
System.err.println(num+"低于限定范围");
}
}
package anomyous;
public class TooBigException extends Exception{
public TooBigException(String message,int num) {
super(message);
System.err.println(num+"超出了限定范围");
}
}
区别一
package anomyous;
public class Test {
public static void main(String[] args) throws TooBigException{
test4(1560);
test5(11);
}
public static void test4(int num)throws TooBigException{
if(num>100){
throw new TooBigException("输入过大产生异常",num);
}
System.out.println("运行良好");
}
public static void test5(int num){//RuntimeException不用加上throws
if(num<50){
throw new TooSmallException("输入过小产生异常",num);
}
System.out.println("运行良好");
}
}
区别二
package anomyous;
public class Test {
public static void main(String[] args) throws TooBigException{
try {
// test5(11);
}catch (TooSmallException e){//RuntimeException注释掉不会报错
}
try{
// test4(154);
}catch (TooBigException e){//Exception注释掉会报错
}
}
public static void test4(int num)throws TooBigException{
if(num>100){
throw new TooBigException("输入过大产生异常",num);
}
System.out.println("运行良好");
}
public static void test5(int num){//RuntimeException不用加上throws
if(num<50){
throw new TooSmallException("输入过小产生异常",num);
}
System.out.println("运行良好");
}
}