Java教程

JAVA---异常---throws处理异常方式

本文主要是介绍JAVA---异常---throws处理异常方式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

异常处理的方式二:throws+异常类型

  • ”throws+异常类型"写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,就会被抛出。异常代码后续的代码,就不会再执行了。
  • try-catch-finally:真正的将异常处理掉了
  • throws的方式只是将异常抛给了方法的调用者。并没有真正将异常处理掉。
package exer;

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

public class ExceptionTest {
	
	public static void main(String[] args) {
		try{
			method2();
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	public static  void method2() throws IOException{
		method1();
	}
	
	public static void method1() throws FileNotFoundException,IOException{
		File file=new File("hello.txt");
		FileInputStream fis=new FileInputStream(file);
		
		int data=fis.read();
		while(data!=-1){
			System.out.println((char)data);
			data=fis.read();
		}
		fis.close();
	}
}

这篇关于JAVA---异常---throws处理异常方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!