异常机制(2021-07-21)
2021/7/22 6:10:25
本文主要是介绍异常机制(2021-07-21),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
异常机制
图片来源
01 Error 和 Exception
02捕获和抛出异常
public class Demo01 { public static void main(String[] args) { int a =1; int b=0; //假设要捕获多个异常:从小到大,从上到下 try { //try监控区域 if(b==0){ //throw throws throw new ArithmeticException();//主动的抛出异常 } 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"); } } } /* Exception finally*/
public class Demo01 { public static void main(String[] args) { try { new Demo01().test(1,0); } catch (ArithmeticException e) { e.printStackTrace(); } finally { } } //假设中方法中,处理不了这个异常。方法上抛出异常 public void test(int a,int b)/*throws ArithmeticException*/{ if(b==0){ //throw throws throw new ArithmeticException(); //主动的抛出异常,一般在方法中使用 } System.out.println(a/b); } }
03自定义异常及经验小结
//自定义异常类 public class MyException extends Exception{ private int detail; public MyException(int a) { this.detail = a; } //toString:异常的打印信息 @Override public String toString() { return "MyException{" + detail + '}'; } }
public class Test { //可能存在异常的方法 static void test(int a) throws MyException { System.out.println("传递的参数为:" + a); if (a > 10) { throw new MyException(a); //抛出 /*try { throw new MyException(a); //抛出 } catch (MyException e) { e.printStackTrace(); } finally { }*/ } System.out.println("ok"); } public static void main(String[] args) { try {//监控区域 test(11); } catch (MyException e) { //捕获异常 //增加一些处理异常的代码~ System.out.println("MyException-》"+e); } finally { } } }
这篇关于异常机制(2021-07-21)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求