Java-java7的异常新特性
Java7的异常新特性:
Android用不到Java7,支持的Java5/java6语法.
----------------------------------------------------------------------------------------
1):增强的throw
2):多异常捕获
3):自动资源关闭
public class MultiCatchDemo { public static void main(String[] args) { String num1 = "50"; String num2 = "2b"; try { int ret1 = Integer.parseInt(num1); // String类型转换为int类型 int ret2 = Integer.parseInt(num2);// String类型转换为int类型 System.out.println("==============="); int ret = ret1 / ret2; System.out.println("结果为" + ret); } catch (ArithmeticException | NumberFormatException e) { //处理算数异常 System.out.println("异常类型1"); e.printStackTrace(); }catch (Exception e) { //都不满足上述异常类型的时候执行这里 ,在所有catch之后 System.out.println("异常类型3"); e.printStackTrace(); } } }
public class AutoCloseDemo { public static void main(String[] args) { test1(); test2(); } private static void test1() { OutputStream out = null; try { // 打开一个资源对象 out = new FileOutputStream("C:/123.txt"); // 操作资源对象 out.write(1); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭资源 try { if (out != null) { out.close(); } } catch (Exception e) { e.printStackTrace(); } } } private static void test2() { try ( // 打开资源对象 OutputStream out = new FileOutputStream("C:/123.txt");) { out.write(1); } catch (Exception e) { // 处理异常 e.printStackTrace(); } } }
共有 0 条评论