25.异常处理

  1. 捕获和处理异常
    用try ……catch ……来捕获异常;
public class ExceptionDemo {
    public static void main(String[] args) {
        String str = "1212a";
        try{
            int a = Integer.parseInt(str); 
        }catch (NullPointerException e){
            e.printStackTrace();
        }catch (NumberFormatException e){
            e.printStackTrace();
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }//捕获方法先小后大
        System.out.println("程序出错"); 
    }
}

finally语句必定会执行,可用于关闭一些接口

public class ExceptionDemo {
    public static void main(String[] args) {
        String str = "1212a";
        try{
            int a = Integer.parseInt(str); 
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return;
        }finally{
            System.out.println("即使有return,finally语句必定会执行,可用于关闭一些接口");
        }
        System.out.println("程序出错"); 
    }
}

输出:
java.lang.NumberFormatException: For input string: “1212a”
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.gavin25.ExceptionDemo.main(ExceptionDemo.java:7)
即使有return,finally语句必定会执行,可用于关闭一些接口

2.throws :把异常向外面抛

public class ExceptionDemo {
    public static void testThrows() throws NumberFormatException{
        String str = "1212a";
        int a = Integer.parseInt(str);
        System.out.println("a");
    }

    public static void main(String[] args) {

        try{
             testThrows();
             System.out.println("这里执行不到");
        }catch (Exception e) {
            // TODO: handle exception
            System.out.println("这里处理异常");
            e.printStackTrace();

        }
        System.out.println("程序出错"); 
    }
}

输出:
这里处理异常
java.lang.NumberFormatException: For input string: “1212a”
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.gavin25.ExceptionDemo.testThrows(ExceptionDemo.java:6)
at com.gavin25.ExceptionDemo.main(ExceptionDemo.java:13)
程序出错


throw
这里写图片描述

未完……

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值