day20 - 异常
在软件程序运行过程中,遇到异常等问题,进行合适的处理,不至于让程序崩溃。
异常发生在程序运行期间,影响了程序的正常流程。
异常和error的区别
-
error一般是致命性的错误,是无法处理和控制的
-
exception可以被程序处理的
1 int a =1; 2 int b =0; 3 try {//try 监控区域: 4 System.out.println(a/b); 5 }catch (Error e){//捕获异常 catch(想要捕获的异常类型) 6 //最高级的是Throwable 7 System.out.println("error"); 8 }catch (Exception m){ 9 System.out.println("exception"); 10 }catch (Throwable t){ 11 System.out.println("throwable"); 12 } finally {//处理善后工作 13 System.out.println("finally"); 14 } 15 //finally 可以不要,在IO,资源的关闭工作使用 16 public class Test { 17 public static void main(String[] args) { 18 try { 19 new Test().test(1,0); 20 } catch (ArithmeticException e) { 21 e.printStackTrace(); 22 } 23 24 } 25 //假设在这个方法中处理不了这个异常,则在方法上抛出异常(throws) 26 public void test(int a,int b) throws ArithmeticException{ 27 if (b==0){ 28 throw new ArithmeticException();//主动抛出异常,一般在方法中使用 29 } 30 System.out.println(a/b); 31 32 } 33 } 34 public class Test2 { 35 public static void main(String[] args) { 36 int a =1; 37 int b =0; 38 //快捷键: CTRL +ALT +T 39 try { 40 41 if (b == 0){// 主动抛出异常 throw throws 42 throw new ArithmeticException(); 43 44 } 45 System.out.println(a/b); 46 } catch (Exception e) { 47 48 } finally { 49 } 50 } 51 }
自定义异常
自定义异常:
1 public class MyException extends Exception{ 2 //传递数字>10抛出异常 3 private int detail; 4 5 public MyException(int a) { 6 this.detail=a; 7 } 8 //toString:打印异常的信息 9 @Override 10 public String toString() { 11 return "MyException{" + 12 "detail=" + detail + 13 '}'; 14 } 15 }
使用异常
1 public class Test { 2 //可能会存在异常的方法 3 static void test(int a) throws MyException { 4 System.out.println("num is : "+a); 5 if(a>10){ 6 throw new MyException(a);//抛出 7 } 8 System.out.println("okok"); 9 10 } 11 12 public static void main(String[] args) { 13 try { 14 test(12); 15 } catch (MyException e) { 16 System.out.println("MyException=>"+e); 17 } 18 19 } 20 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗