第七章-3·异常

异常(Excoption)

分类

  • Throwable
    • 错误Error(不可处理)
      • VirtuMachineError
      • AWTError
    • 异常Exception(可以处理)
      • IOException:
      • RuntimeException:

异常处理(try,catch,finally,throw,throws)

捕获异常


格式

try{
    异常语句
}catch(Exception e){
}finally{
    一定会执行的代码
}

例子

package ooday05;
//异常捕获
public class Demo {
   /* public static void main(String[] args) {
        int a=1;
        int b=0;
        System.out.println(a/b);//异常:Exception in thread "main" java.lang.ArithmeticException:
    }*/
   public static void main(String[] args) {
       int a=1;
       int b=0;
       try {//监控区域
           System.out.println(a/b);
       }catch (ArithmeticException e){//捕获异常    ArithmeticException:捕获的异常类型
           System.out.println("程序程序异常,变量不能为0");
       }finally {//处理善后工作
           System.out.println("finally");
       }

   }
}
package ooday05;
//异常捕获
public class Demo01 {
    public static void main(String[] args) {
        int a=1;
        int b=0;
        try {
            System.out.println(a/b);//快捷键:ctrl+alt+T
        } catch (Exception e) {
            System.exit(1);//结束运行
            e.printStackTrace();//打印错误的栈信息
        } finally {
            System.out.println("finally");
        }
    }

}

抛出异常


throws关键字
package ooday05;
//抛出异常
public class Demo02 {
    public static void main(String[] args) throws Exception {
        try {
            n();
        } catch (ArithmeticException e) {
            System.out.println(e);
        } finally {
            System.out.println("finally");
        }

    }
   public static void n() throws ArithmeticException{
       int a=1;
       int b=0;
       System.out.println(a/b);
    }
}

throw关键字
package ooday05;
//抛出异常 throw
public class Demo03 {
    public static void main(String[] args) {
        try {
            throw new Exception("实例化异常对象");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

自定义异常


直接继承Exception就可以来完成自定义异常类

package ooday05;

class MyException extends Exception{
    public MyException(String msg){
        super(msg);
    }
}

public class Demo04 {
    public static void main(String[] args) {
        try {
            throw new MyException("自定义异常");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
  • 12
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值