如果要在一段代码中抛出一个已检查的异常,有两个选择:
- 使用
try-catch
块处理已检查的异常。 - 在方法/构造函数声明中用
throws
子句指定。
语法
throws
子句的一般语法是:
<modifiers> <return type> <method name>(<params>) throws<List of Exceptions>{
}
关键字throws
用于指定throws
子句。throws
子句放在方法参数列表的右括号之后。throws
关键字后面是以逗号分隔异常类型的列表。
示例-1
以下代码显示如何在方法声明中使用throws
子句
import java.io.IOException;
public class Main {
public static void readChar() throws IOException {
int input = System.in.read();
}
}
这里是显示如何使用它的代码。
实例-2
在调用方法中捕捉抛出的异常 -
import java.io.IOException;
public class Main {
public static void readChar() throws IOException {
int input = System.in.read();
System.out.println(input);
}
public static void main(String[] args) {
try {
readChar();
} catch (IOException e) {
System.out.println("Error occurred.");
}
}
}
上面的代码生成以下结果(输入-1
回车,得到以下结果)。
-1
45
实例-3
继续 实例-2 直接抛出异常。
import java.io.IOException;
public class Main {
public static void readChar() throws IOException {
int input = System.in.read();
System.out.println(input);
}
public static void main(String[] args) throws IOException {
readChar();
}
}
上面的代码生成以下结果(输入-1
回车,得到以下结果)。
-1
45
抛出异常
可以使用throw
语句在代码中抛出异常。throw
语法的语法是 -
throw <A throwable object reference>;
throw
是一个关键字,后面跟着一个可抛出对象的引用。throwable
对象是一个类的实例,它是Throwable
类的子类,或Throwable
类本身。
以下是throw
语句的示例,它抛出一个IOException
:
// Create an object of IOException
IOException e1 = new IOException("File not found");
// Throw the IOException
throw e1;
可以创建一个throwable
对象并将其放在一个语句中。
// Throw an IOException
throw new IOException("File not found");
如果抛出一个被检查的异常,必须使用try-catch
块来处理它,或者在方法或构造函数声明中使用throws
子句。
如果抛出未经检查的异常,上面的这些规则不适用。
上一篇:
Java异常处理教程
下一篇:
Java自定义异常