异常
异常
-
Error
- 由jvm生成并抛出,大多数错误与代码编写者所执行的操作无关
- jvm不再有继续执行操做所需要的内存资源时,出现OutOfMenoryError。线程终止。
-
Exception
- 由程序逻辑错误引起
public class Application { public static void main(String[] args) { int a = 1; int b = 0; //多个异常时从小到大 try{ System.out.println(a/b); new Application().a(); }catch (Exception e){ System.out.println("异常1"); }catch (Throwable e)//想要捕获的类型 { System.out.println("异常2"); }finally {//io,资源关闭 System.out.println("finally"); } //ctrl+alt+t try { System.out.println(a/b); } catch (Exception e) { e.printStackTrace(); } finally { } new Application().test(a,b); } public void a(){ b(); } public void b(){ a(); } //假设在这个方法中,处理不了这个异常,可以往上抛 public void test(int a, int b) throws ArithmeticException{ if(b==0){ throw new ArithmeticException();//主动抛出异常,一般在方法里使用 } System.out.println(a/b); } }
- 自定义异常
public class MyException extends Exception{ //传递数字>10 private int detail; public MyException(int a){ this.detail = a; } @Override public String toString() { return "MyException{" + "detail=" + detail + '}'; } } public class Test { static void test(int a) throws MyException{ System.out.println("a=" + a); if(a > 10){ throw new MyException(a); } } public static void main(String[] args) { try { test(13); }catch (MyException e){ System.out.println("exception"); } } }
- 总结
- 多重catch后,加一个catch(Exception)来处理可能被遗漏的异常
- 添加finally释放占用的资源
本文作者:n1ce2cv
本文链接:https://www.cnblogs.com/sprinining/p/14528650.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步