异常处理与自定义异常

异常处理

  • Throwable是异常的基类,分为error和exception,在编程中我们关注exception
  • 在开发中,我们需要把可能异常的代码使用try语句包裹起来
  • catch可以有多个,顺序为从子类到父类,大的放后,小的放前
  • finally:无论是否异常都会进行处理
  • throw抛出一个异常,在方法内部使用,throws在方法后面声明,由方法调用者处理
  • exception分为编译期异常(exception受检)和运行期异常(RuntimeException非受检)

例如:

public class Test1 {
    public static void main(String[] args){
        try {
            div2(12,0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("程序结束2");
        input();
    }

    private static int div2(int num1,int num2) throws ArithmeticException{
        try{
            int result = num1/num2;
            System.out.println(result);
            return result;
        }catch (ArithmeticException e){
            throw new ArithmeticException("除数不为0");
        }
    }
}

自定义异常

  • Exception : 受检异常,在编程期间检查,在调用抛出这个异常方法时,必须是显示的使用try catch
  • RuntimeException :非受检异常,在运行期间检查,在调用这个方法时,可以不用显示的使用try catch
  • 在使用自定义异常时,根据实际的业务要求,来决定使用哪个来作为父类

# 案列:如果用户名字不对抛出一个异常信息(用户名错误)

定义一个异常类(这里我继承的Exception类)

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

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

账号类(用来提供账号和密码)

public class Account {
    private String name;
    private int password;

    public Student(String name, int password) {
        this.name = name;
        this.password = password;
    }
    // get,set,toString方法
}

校验账号密码类(用来检查账号是否正确)

public class AccountService {
    public Account check(String name, int password) throws Exception {
        if (!"admin".equals(name)) {
            throw new MyException("用户名错误");
        }
        if (password != 123456) {
            throw new Exception("用户密码错误");
        }
        return new Student(name, password);
    }
}

测试:

public class Test2 {
    public static void main(String[] args) {
        AccountService service = new AccountService();
        try {
            Account account = service.check("admin", 123456);
            System.out.println(student);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

常见异常:

  • ArithmeticException :算术运算异常
  • ArrayIndexOutBoundsException:下标越界异常
  • NullPointerException:空指针异常
  • InputMisMatchException:输入不匹配异常
  • RunTimeException:运行异常
  • Exception:异常
  • ClassNotFoundException:类找不到异常
  • ClassCaseException:类型转换异常
  • DateFomatException:日期格式化异常
  • IoException:Io异常
  • SqlException: sql异常
posted @   JamieChyi  阅读(21)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示