异常
异常
1.捕获和抛出异常
-
异常处理五个关键字
- try
- catch
- finally
- throw
- throws
-
捕获异常
public class Demo { public static void main(String[] args) { int a = 1; int b = 0; //捕获多个异常:从小到大 try{ //try监控区域 System.out.println(a/b); }catch (ArithmeticException e) { System.out.println("程序异常,b不能为0"); }catch (Error e) { System.out.println("Error"); }catch (Exception e) { System.out.println("Exception"); }catch (Throwable t) { System.out.println("Throwable"); }finally { //处理善后工作 System.out.println("finally"); } //finally 可以不要 } } -
抛出异常
public class Demo { public static void main(String[] args) { new Demo().test(1,0); } //假设方法中,处理不了这个异常。方法上抛出异常 throws public void test(int a,int b) throws ArithmeticException { if (b == 0) { //throw throw new ArithmeticException();//主动抛出异常,一般再方法中使用 } } }
2.实际应用中的经验总结
- 处理运行时异常时,采用逻辑去合理规避同时辅助 try-catch处理
- 在多重 catch块后面,可以加一个 catch(Exception)来处理可能会被遗漏的异常
- 对于不确定的代码,也可以加上 try-catch,处理潜在的异常
- 尽量去处理异常,而不是简单地调用 printStackTrace()去打印输出
- 具体如何处理异常,要根据不同的业务需求和异常类型去决定
- 尽量添加 finally语句块去释放占用的资源【IO、Scanner】

浙公网安备 33010602011771号