您的位置:首页 > 编程语言 > Java开发

Java异常处理 “受控(checked)”的异常

2015-11-14 20:52 381 查看
示例程序:

public class TestThrows   {
public static void main(String[] args)     {
FileInputStream fis = new
FileInputStream("a.txt");
}
}


为什么以上程序完全符合Java语法规范,但是却会报错呢?

修正:

public class TestThrows
{
public static void main(String[] args)
throws FileNotFoundException
{
FileInputStream fis = new
FileInputStream("a.txt");
}
}


throws语句表明某方法中可能出现某种(或多种)异常,但它自己不能处理这些异常,而需要由调用者来处理。
当一个方法包含throws子句时,需要在调用此方法的代码中使用try/catch/finally进行捕获,或者是重新对其进行声明,否则编译时报错。

受控与不受控的异常

throws语句中声明的异常称为受控(checked)的异常,通常直接派生自Exception类。
RuntimeException(其基类为ExceptionError(基类为Throwable)称为非受控的异常。这种异常不用在throws语句中声明。
CheckedExceptionDemo.java示例展示了上述两种异常的特性。


抛出多个受控异常的方法
一个方法可以声明抛出多个异常

int g(float h) throws OneException,TwoException { …… }
例如:

import java.io.*;
public class ThrowMultiExceptionsDemo {
public static void main(String[] args)
{
try {
throwsTest();
}
catch(IOException e) {
System.out.println("捕捉异常");
}
}

private static void throwsTest()  throws ArithmeticException,IOException {
System.out.println("这只是一个测试");
// 程序处理过程假设发生异常
throw new IOException();
//throw new ArithmeticException();
}
}


结果截图:



注意一个Java异常处理中的一个比较独特的地方:

当一个方法声明平抛出多个异常时,再次方法调用语句处只要catch其中任意一个异常,代码就可以顺利编译。

子类抛出受控异常的限制:

一个子类的throws子句抛出的异常,不能是其基类同名方法抛出的异常对象的父类。

import java.io.*;

public class OverrideThrows
{
public void test()throws IOException
{
FileInputStream fis = new FileInputStream("a.txt");
}
}
class Sub extends OverrideThrows
{
//如果test方法声明抛出了比父类方法更大的异常,比如Exception
//则代码将无法编译……
public void test() throws FileNotFoundException
{
//...
}
}


Java 7 及以后的版本,允许在一个catch块中捕获多个异常。
例如:

try {
//...
throw new SocketException();
}
catch (SocketException | SecurityException | NullPointerException e) {
//exception handler
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: