码迷,mamicode.com
首页 > 其他好文 > 详细

捕获异常的两种方式Exception

时间:2015-07-12 00:11:31      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

1、抛出异常:让调用此方法的代码去管

public static void GetFile() throws Exception{}

package com.throwable;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;

public class ExcetionDemo {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
           
		try {
			GetFile() ;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
            
	}
	
	public static void GetFile() throws Exception{
		 File file = new File("c:\\test.java");
         FileInputStream fis = new FileInputStream(file);
         BufferedReader br = new BufferedReader(new InputStreamReader(fis));
         //Unhandled exception type FileNotFoundException
         //2 quick fixed available: add Throwable ; surrownd try/catch
         String line = br.readLine();
         System.out.println(line);
         //输出结果:heheheheh
         
	}

}

  

2. 在当前要出现异常的代码块周围,try --catch

package com.throwable;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExcetionDemo2 {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
			GetFile() ;
	}
	
	public static void GetFile(){
		 File file = new File("c:\\test.java");
         FileInputStream fis;
		try {
			fis = new FileInputStream(file); 
			BufferedReader br = new BufferedReader(new InputStreamReader(fis)); 
			 //Unhandled exception type FileNotFoundException
			//2 quick fixed available: add Throwable ; surrownd try/catch
            String line;
			line = br.readLine();
            System.out.println(line);
         //输出结果:heheheheh
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    
	}

}

  

 

捕获异常的两种方式Exception

标签:

原文地址:http://www.cnblogs.com/childhooding/p/4639587.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!