throw显示未处理异常
时间: 2023-12-03 13:45:33 浏览: 47
在程序中,当一个异常被抛出时,如果没有适当地处理它,它将成为一个未处理异常。此时,可以使用 `throw` 关键字来显示地抛出异常。
下面是一个简单的示例:
```java
public class Test {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println(result);
} catch (Exception e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
public static int divide(int dividend, int divisor) throws Exception {
if (divisor == 0) {
throw new Exception("Divisor cannot be zero!");
}
return dividend / divisor;
}
}
```
在上面的代码中,`divide` 方法会检查除数是否为零,如果是,则使用 `throw` 关键字抛出一个新的 `Exception` 对象,并将错误信息作为参数传递给该对象。在 `main` 方法中,我们使用 `try-catch` 块来处理 `divide` 方法可能抛出的异常。如果异常被抛出,我们将捕获它并打印出错误信息。
注意,当使用 `throw` 抛出异常时,需要指定要抛出的异常类型。在上面的示例中,我们抛出的是 `Exception` 类型的异常。