学习自B站:【狂神说Java】Java零基础学习视频通俗易懂
Java基础(异常机制)
抛出异常
捕获异常
异常处理的五个关键字
try、catch、finally、throw、throws
package com.HJX.exception; 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("程序出现异常"); }finally { //finally:处理善后工作(可以不写) System.out.println("finally"); } } }
package com.HJX.exception; public class Test { public static void main(String[] args) { int a = 1; int b = 0; //假设要捕获多个异常,要从小到大去捕获 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 { //finally:处理善后工作(可以不写) System.out.println("finally"); //显示这行 } } }
package com.HJX.exception; public class Test2 { public static void main(String[] args) { int a = 1; int b = 0; //利用快捷键:Ctrl + Alt + T try { System.out.println(a/b); } catch (Exception e) { System.exit(0); //程序结束 e.printStackTrace(); //打印错误的栈信息 } finally { } } }
package com.HJX.exception; public class Test { public static void main(String[] args) { new Test().test(1,0); } //假设这个方法中处理不了这个异常,在方法中来抛出异常 public void test(int a,int b) throws ArithmeticException{ if(b == 0){ //throw throws throw new ArithmeticException(); //主动的抛出异常,一般在方法中使用 } System.out.println(a/b); } }
package com.HJX.exception.demo02; //自定义的异常类 public class MyException extends Exception{ //传递数字 > 10L private int detail; public MyException(int a) { this.detail = a; } //toString:异常的打印信息 @Override public String toString() { return "MyException{"+ detail +'}'; } } ----------------------------------------------- package com.HJX.exception.demo02; public class Test { //可能会存在异常的方法 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); } } }