Exception异常是指程序运行过程中出现了不期而至的各种状况 简单分类
检查性异常,程序员无法预见的运行时异常错误ERROR 异常体系结构
Java把异常当作为一个类来处理,,并定义了一个基类java.lang.Throwable作为所有异常的超类(父类)Error和Exception Error
Error类对象由Java虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关Java虚拟机运行错误,JAM不再具有继续执行操作所需内存资源时,将会出现OutOfMemoryError。发生时,Java虚拟机线程终止 Exception
RuntimeException(运行时异常),编译无法通过,应从程序逻辑上避免非运行时异常 异常处理机制
抛出异常捕获异常关键字:try、catch、finally、throw、throws
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { //try监控区域
System.out.println(a/b);
}catch (ArithmeticException e){ //catch 捕获异常
System.out.println("程序出现异常,变量不能为0");
}finally { //处理善后工作
System.out.println("finally");
}
//finally 可以不要finally ,假设IO,资源。关闭
}
}
//假设要捕获多个异常:从小到大
try { //try监控区域
System.out.println(a/b);
}catch (Error e){ //catch 捕获异常
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable t){
System.out.println("Throwable");
}
finally { //处理善后工作
System.out.println("finally");
}
public static void main(String[] args) {
try {
new Test().test01(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
//假设这方法中,处理不了这个异常,在方法上抛出异常
public void test01(int a, int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException(); //主动抛出异常,一般在方法中使用
}
//System.out.println(a/b);
//Exception in thread "main" java.lang.ArithmeticException
}
自定义异常
自定义异常,继承Exception类即可步骤;
创建自定义异常类在方法中通过throw关键字抛出异常对象通过try catch捕获
//自定义异常类
public class MyException extends Exception{
//传递数字,大于10,抛出异常
private int detail;
public MyException(int a) {
this.detail = a;
}
//toString:异常的打印信息
@Override
public String toString() {
return "MyException{" + detail + '}';
}
}
public class Test03 {
//可能会存在异常的方法
static void test(int a) throws MyException {
System.out.println("传递的参数为"+a);
if (a>10) {
throw new MyException(a); //抛出
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
System.out.println("MyException=>"+e);
}
}
}
总结
处理运行异常时,采用逻辑去合理规避同时辅助try-catch在多重catch块后面,可以加一个catch(Exception)来处理可能会遗漏掉的异常对于不确定的代码块,加上try-catch,处理潜在异常尽量去处理异常,切记加简单的输出异常具体如何处理更具不同的业务需求而定尽量添加finally语句块去释放占用的资源,IOScanner



