java 中Throwable常用方法



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


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("清理垃圾");
		}
	}

	

}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值