java异常
运行时异常:RuntimeException可处理可不手动处理,继承了exception类
非运行时异常:Exception 必须需要手动处理,捕获并抛出。
异常的代码结构
try{
//可能出现异常的代码块
}catch1(异常类型 ){
//处理异常,并抛出
}
catch2(异常类型 ){
//处理异常,并抛出
}finally{
//出不出现异常都会执行此个代码块,一般用来关闭流
}
{
Scanner scanner = new Scanner(System.in);
//System.out.println("输入数字:");
try {
// int i = scanner.nextInt();
//int result = i/0;
//手动抛出异常
Exception exception = new Exception("非运行时异常");
//throw exception;
throw new RuntimeException("手动运行时异常");
}catch (ArithmeticException a){//数字运算异常
System.out.println("除数不能为0");
}
catch (RuntimeException r){
System.out.println("手动捕获运行时异常");
}
catch (Exception e){
System.out.println("请输入一个整数");
}
finally {
System.out.println("finally 模块,程序失败与否都可以执行~");
}
System.out.println("程序执行完毕!");
}
自定义异常
自定义异常一般为运行时异常,需要继承父类异常类(RuntimeException)。
package com.salted.fish.collections.shop.exceptioncustom;
public class BalanceInsufficientException extends RuntimeException{
public BalanceInsufficientException() {
}
public BalanceInsufficientException(String message) {
super(message);
}
}