标签:系统 编译 system except 方式 run 使用 自己 保存
异常分类:
Error:系统内部错误或者资源耗尽(不用太管);
Exception:程序有关的异常(重点关注);
java程序相关异常又分为:
try-catch-finally:一种保护代码正常运行的机制。
结构:
代码示例:
public class TryDemo { public static void main(String[] args) { try { int a = 5/2; //无异常 System.out.println("a is " + a); } catch(Exception ex) { ex.printStackTrace(); } finally { System.out.println("Phrase 1 is over"); } try { int a = 5/0; //ArithmeticException System.out.println("a is " + a); } catch(Exception ex) { ex.printStackTrace(); } finally { System.out.println("Phrase 2 is over"); } try { int a = 5/0; //ArithmeticException System.out.println("a is " + a); } catch(Exception ex) { ex.printStackTrace(); int a = 5/0; //ArithmeticException } finally { System.out.println("Phrase 3 is over"); } } }
多catch块处理:
嵌套结构:
try结构中,如果有finally块,finally肯定会被执行。
try-catch-finally每个模块里面会发生异常,所以也可以在内部继续写一个完整的try结构。
try {
try-catch-finally
}
catch() {
try-catch-finally
}
finally {
try-catch-finally
}
代码示例:
public class ThrowsDemo { public static void main(String [] args) { try { int result = new Test().divide( 3, 1 ); System.out.println("the 1st result is" + result ); } catch(ArithmeticException ex) { ex.printStackTrace(); } int result = new Test().divide( 3, 0 ); System.out.println("the 2nd result is" + result ); } } class Test { //ArithmeticException is a RuntimeException, not checked exception public int divide(int x, int y) throws ArithmeticException { int result = x/y; return x/y; } }
标签:系统 编译 system except 方式 run 使用 自己 保存
原文地址:https://www.cnblogs.com/Yunus-ustb/p/12887718.html