异常处理

Java异常机制可以是程序的异常处理代码和正常的业务代码分离,保证程序代码的健壮性。

public class ExceptionMsg {
    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new FileInputStream("a.txt");
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());//输出错误信息:a.txt (系统找不到指定的文件。)
            System.out.println(e.getStackTrace().toString());
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }
}
输出错误的堆栈信息:

java.io.FileNotFoundException: a.txt (系统找不到指定的文件。)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at ExceptionMsg.main(ExceptionMsg.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)


如果需要关闭一些系统资源,可以在finally下执行,但是如果先执行了System.exit(1);则finally将不会被执行。

throw抛出异常 

当不知道该如何处理异常的时候,可以使用throws声明抛出异常。

当因业务需求不满足时,也可以使用抛出异常。

抛出异常有两种方式:1.checked异常:编译时异常,需要使用try catch 来捕获 ,或者 交给改带throws方法的调用者    2.runtime异常:则可以不用处理异常,交给焦永志

public class ExceptionMsg {
    public static void main(String[] args) {
        try {
            //需要显示的捕获异常
            throwChecked(1);
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        throwRunTime(1);

    }
    public static void throwChecked(int a) throws Exception{
        if (a>0){
            //自行抛出异常,则需要在try块里,或者处于throws声明方法中
            throw  new Exception("……");
        }
    }

    public static  void throwRunTime(int a) {
        if (a >0){
            //可以完全不用理会该异常,把异常交给方法调用者处理
            throw  new RuntimeException("……");
        }
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值