本文共 1872 字,大约阅读时间需要 6 分钟。
String getMessage() 返回此 throwable 的详细消息字符串
String toString() 返回此 throwable 的简短描述
void printStackTrace() 打印异常的堆栈的跟踪信息
package com.itheima_01;/* * Throwable的常用方法: String getMessage() String toString() void printStackTrace() * */public class ExceptionDemo4 { public static void main(String[] args) { try { System.out.println(2 / 0); } catch (ArithmeticException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void method() { try { System.out.println(2 / 0); } catch(ArithmeticException e) { //String getMessage() : 原因 //System.out.println(e.getMessage()); //String toString() 类型和原因 //System.out.println(e.toString()); //void printStackTrace():类型原因和位置 e.printStackTrace(); } //System.out.println("hello"); }}
finally使用格式:
try{
}catch(异常类型 异常变量){
}finally{
//释放资源的代码
}
package com.itheima_01;import java.io.FileWriter;import java.io.IOException;/* * finally:组合try...catch使用,用于释放资源等收尾工作,无论try...catch语句如何执行,finally的代码一定会执行 * * try { * 有可能出现问题的代码; * * } catch(异常对象) { * 处理异常; * } finally { * 释放资源; * 清理垃圾; * } * */public class ExceptionDemo5 { public static void main(String[] args) { //method(); FileWriter fw = null; try { System.out.println(2 / 0); fw = new FileWriter("a.txt"); fw.write("hello"); fw.write("world"); //System.out.println(2 / 0); fw.write("java"); //fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { //释放资源 try { if(fw != null) { fw.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private static void method() { try { System.out.println(2 / 1); } catch(ArithmeticException e) { System.out.println("除数不能为0"); } finally { System.out.println("清理垃圾"); } } }
转载地址:http://unjqb.baihongyu.com/