Java之异常处理

文章目录

Java之异常处理

  • 基础说明
/*
*异常处理(Throwable-->Error,Exception):
* 编译时异常(javac...):1.FileNotFoundException 必须处理,否则程序不执行
* 运行时异常(java...):
* 1.NullPointException
* 2.ArrayIndexOutOfBounds
* 异常处理的抓抛模型:
* 抛(发生异常):当程序在正常的执行过程中,如果执行的某行代码发生异常,
* 则JVM(系统)将会根据异常的类型创建对应异常的对象并抛出来,同时终止程序的运行。
* 系统抛出异常-----手动抛出异常。
* 抓(处理异常):
* 1.try-catch-finally
* 格式:try{
* 可能会发生异常的代码;
* }catch(异常类1 变量名){
* 处理异常1的代码;
* }catch(异常类2 变量名){
* 处理异常2的代码;
* }
* .....
* 【finally{
* 一定会执行的代码;
* }】
* ①不知道是何种异常的话,使用Exception(父类)
* ②catch 也可省略
* ③catch中再发生异常,finally也会执行。
* 2.throws
* 格式:
* throws 异常类型1....
* 自己本身没有处理异常,而是向上抛出异常,谁调用谁处理
* 使用场景:
* try-catch-finally-->真正需要处理异常的时候
* throws-->父类被重写的方法没有throws子类重写的方法也不能throws
* 子类抛出异常不大于父类抛出异常
* */

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class TestException {
    public static void main(String[] args) {
//      //运行时异常
//        int[] nums=new int[2];
//        System.out.println("aaa");
//        try{
//            System.out.println(nums[2]);
//            //ArrayIndexOutOfBoundsException
//            System.out.println(1 / 0);
//            //ArithmeticException
//        }catch(Exception e){
//            System.out.println(e.getMessage());
//            e.printStackTrace();//详细信息,输入进日志
//        }finally {
//            System.out.println("一定会执行的!");
//        }
        TestException te=new TestException();
        //te.demo1();demo1()处理不了,谁调用谁处理

    }
    public void test(){
        System.out.println("test()");
    }
    public void demo(){
        System.out.println("Demo()");
    }
    //抛出异常
    public void demo1() throws FileNotFoundException {
        new FileInputStream("123.txt");
    }

}
/*
* throw(制造异常):手动抛出异常
* 格式:throw new 异常类对象(只能是运行时异常)
*/
//class TestThrow{
//    public static void main(String[] args) {
//        TestThrow te =new TestThrow();
//        te.test();
//    }
//    public void test(){
//       setAge(-5);
//        System.out.println("程序执行完毕");
//    }
//    public void setAge(int age) {
//        if (age<0){
//            age=10;
//            //System.out.println("你写错了!");
//            //抛异常,如果设计不合理,抛出异常,终止程序
//            throw new NullPointerException("不能小于零");
//        }
//    }
//}
//自定义异常类:
//        * 1.自定义一个类并继承Exception(编译时异常)或者RuntimeException。
//        * 2.提供两个构造器,一个空参,一个有参(调用父类的有参构造器)
class MyException extends RuntimeException{
    public MyException(){

    }
    public MyException(String message){
        super(message);
    }
}

public MyException(){

}
public MyException(String message){
    super(message);
}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值