java--异常处理

异常处理

我们在写代码时,经常出现的一些小问题,为了方便我们处理,java为我们提供了异常机制
捕获异常与抛出异常

//捕获异常格式:
	 try {
         //可能出错的语句
     } catch (出错的类型 出错的对象) {
         //出错后的处理
     }

//eg:
	try{
		System.out.println(1);
		System.out.println(2/0);
		System.out.println(3);
	} catch(ArithmeticException ae){
		System.out.println(4);
	}
	System.out.println(5);
	// 1  4  5

//eg2:
	try{
		//String s=null;
		//s.length();
		char[] chs = new char[5];
		System.out.println(chs[5]);
	}catch(NullPointerException ne){
		System.out.println("空指针异常");
	}catch(Exception e){					//当有其他未知异常时,实例化异常的父类对象,捕获未知异常
		System.out.println("其他异常");
	}



//void printStackTrace(java.io.PrintWriter s) 
//通用方式,打印异常类型,位置,与java虚拟机自己捕获异常类型不同的是,这个异常打印后,还会继续执行下面的语句
	try{
		char[] chs = new char[5];
		System.out.println(chs[5]);
	}catch(Exception e){
		e.printStackTrace();
	}
	System.out.println("----");
 

//finally: 不论是否捕获到异常都会执行的部分,常用于释放资源,清理垃圾
	try(){
		//有可能出现问题的代码;
	} catch(异常对象){
		//处理异常
	} finally{
		//释放资源;
		//清理垃圾
	}


finallyDemo

//鲁棒版文件写入
	public static void main(String[] args) {
		function("a.txt");
	}
	
	public static void function(String filename){
		FileWriter fw = null;
		try {
			//System.out.println(1/0);;
			fw = new FileWriter(filename);
			fw.write("hello world");
			fw.write("hello world");
			//fw.write(2/0);
			fw.write("hello world");
			fw.write("hello world");
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(fw!=null)
					fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
	}

抛出异常(throw)

throw new RuntimeException("抛出运行时异常");  //抛出运行时异常
throw new Excepption("抛出编译时异常");

//自定义异常类  继承RuntimeException 或者是 Exception
public class MyException extends RuntimeException{
	
	public MyException()
	{
		super();
	}
	
	public MyException(String s)
	{
		super(s);
	}
}

posted @ 2019-06-23 11:52  it-pupil  阅读(321)  评论(0编辑  收藏  举报