java 中Throwable常用方法

来源:互联网 发布:淘宝背景材图 编辑:程序博客网 时间:2024/06/05 14:39



Throwable常用方法



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 blocke.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概述和应用场景


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 blocke.printStackTrace();} finally {//释放资源try {if(fw != null) {fw.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}private static void method() {try {System.out.println(2 / 1);} catch(ArithmeticException e) {System.out.println("除数不能为0");} finally {System.out.println("清理垃圾");}}}



原创粉丝点击