Java中的try-catch速记

1、无论如何都会执行finally,即使在catch部分已经return了
但是try-catch后面部门的代码将不执行了(跳出函数)

链接:https://www.nowcoder.com/questionTerminal/ffb26e7e10574ba7b14577f3e328fde7
来源:牛客网

package algorithms.com.guan.javajicu; 
public class TestDemo { 
    public static String output =""; 
    public static void foo(int i){ 
       try{ 
           if(i == 1){ 
              throw new Exception(); 
           } 
       }catch(Exception e){ 
           output += "2"; 
           return ; 
       }finally{ 
           output += "3"; 
       } 
       output += "4"; 
    } 

    public static void main(String[] args) { 
       foo(0); 
       foo(1); 
       System.out.println(output);  // 3423
    } 
}

2、再try-catch执行return之后后面的代码不能执行了

如上代码。最后的output += "4"; 不再执行

3、所有的异常类都继承子Throwable类,这个类又有两个子类:Error类以及Exception类,Error属于系统内部错误,不可捕获,会直接导致程序中断,Exception属于可捕获异常,其中有分为运行时异常(数组越界等),属于Java虚拟机生成的异常,非运行时异常(编译时异常如IOException)
4、Java编译器要求Java程序必须捕获或生命所有的非运行时异常如FileNotFoundException/IOException,但是对于运行时异常可以不做处理,因为这种异常很普遍
5、常见异常:
ArithmeticException (被0除)
ArrayIndexOutOfBoundsExcetion (数组下标越界)
NullPointerException (试图用.访问不存在的属性或方法)
NumberFormatException (将非数字字符串转换为字符串) String stage = “34L”; int age = Integer.parseInt(stage);
StringIndexOutOfBoundsException (字符串越界) String name = “jdfjdkfdf”; char ch = name.charAt(name.length());
ArrayStoreException (数组类型不兼容) Object[] b = new Boolean[5]; b[0] = “nihao”;
ClassCastException (描述强制类型转换时的异常) Object obj = new String(“333”); Integer s = (Integer) obj;
6、不能讲子类异常放在父类异常的后面,否则会出错,因为这样永远到达不了子类的Exception,在java中不能到达的代码是一个错误

int numbers[] = new int[3];
try{
    numbers[0] = 1;
    numbers[2] = numbers[0] / 0;
}catch(Exception e){
    System.out.println(e.toString());
}catch(ArithmeticException e){   // 这个catch永远轮不到,编译出错
    e.toString();
}

7、为了执行try块中所有的代码,捕获所有可能产生的异常,可以使用嵌套try语句。

public static void main(String[] args) {
    String friends[] = {"zhou", "yun", "jin"};
    try {
        try{
            int num = friends.length/0;
        }catch(ArithmeticException e){   // 捕获除0异常
            e.printStackTrace();
        }
        for(int i=0;i<=4;i++){
            System.out.println(friends[i]);
        }
    }catch(ArrayIndexOutOfBoundsException e){  // 即使发生了除0异常也可以捕获数组越界异常
        e。printStackTarce();
    }
}

8、如果一个方法不想在本函数内捕获异常,可以在方法声明后面使用throws可以向上传递异常,由调用它的方法来处理异常
如:

public static int compute(int x)  throws ArithmeticException {}

9、可以使用throw来定义一个自定义的异常
10、在try 块中的变量是局部变量,在使用throw语句跑出异常对象时,该语句后面的代码将不会执行,所以,一般情况下throw语句应该放在条件语句里面,或者放到最后面
11、自定义异常类:
(1)创建自定义异常类
(2)在方法中通过throw抛出异常对象
(3)在当前抛出异常的方法中处理异常,使用try。。。catch捕获并且处理。否则在方法的声明处通过throws指明要调用的异常
(4)在出现异常的方法调用代码中捕获并处理的异常

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值