【HC】Java中的异常处理
Java中的异常处理http://cdn.u1.huluxia.com/g3/M03/36/DB/wKgBOV3H0MWAAQKxAAEYAGmpuHk141.jpg
在这里插入图片描述示例1:public static void main(String[] args) { try { System.out.println(3/0); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("finally"); }}123456789结果:http://cdn.u1.huluxia.com/g3/M03/36/DB/wKgBOV3H0MWAXt0HAABAAMxr1vE115.jpg
在这里插入图片描述示例:Multi-catchpublic static void main(String[] args) { int d = new Scanner(System.in).nextInt(); try { System.out.println(3 / d); new File("G:/dd/aa/ab.txt").createNewFile(); } catch (ArithmeticException e) { e.printStackTrace(); } catch (IOException e) { // System.out.println(e.getMessage()); e.printStackTrace(); } //可以简写为 try { System.out.println(3 / d); new File("G:/dd/aa/ab.txt").createNewFile(); } catch (ArithmeticException | IOException e) { e.printStackTrace(); }}12345678910111213141516171819示例:实现一:抛出异常 public static void main(String[] args) throws IOException { File file = new File("pom.xml"); FileReader reader = new FileReader(file); char[] buf = new char; int len = -1; while((len = reader.read(buf))!= -1){ String res = new String(buf, 0, len); System.out.println(res); } reader.close(); }1234567891011实现二:捕获异常public static void main(String[] args) { File file = new File("pom.xml"); FileReader reader = null; try { reader = new FileReader(file); char[] buf = new char; int len = -1; while ((len = reader.read(buf)) != -1) { String res = new String(buf, 0, len); System.out.println(res); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } }}12345678910111213141516171819202http://cdn.u1.huluxia.com/g3/M03/36/DB/wKgBOV3H0MaAOThGAAB7c6R6rKQ898.jpg
页:
[1]