java - 在 Eclipse 中提示“未处理的异常类型 xxx”
问题描述
我不认为我真的理解 try-catch 块和 throws 。
public class TestException {
public static void main(String[] args) {
new TestException().tt();
}
public void tt() {
try {
throw new RuntimeException();
}catch (Exception e) {
throw e;
}
}
}
在 Eclipse 中,有一个关于“未处理的异常类型 xxx”的错误提示,如果你运行它,你会得到一个
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type Exception
但是在 Idea 中,没有错误。它运行并正确抛出异常。
在我看来,'e' 没有被声明为 RuntimeException(尽管它是一个 RuntimeException),所以 tt() 方法必须用 throws 声明。但实际上并非如此。为什么?
解决方案
这应该回答你的问题:
public class TestException {
public static void main(String[] args) {
new TestException().tt();
}
public void tt() {
try {
throw new RuntimeException();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
如果你使用throws,你会告诉那些使用你的函数的人,“我的函数可能会抛出异常。你必须处理它。”
你应该在这句话中得到throws和throws的区别。
如果您使用 try-catch,您将处理该异常。
1)您应该添加throws关键字,如下所示
public class TestException {
public static void main(String[] args) {
new TestException().tt();
}
public void tt() **throws Exception** {
try {
throw new RuntimeException();
}catch (Exception e) {
throw e;
}
}
}
2) 处理使用函数的异常
public class TestException {
public static void main(String[] args) {
try{
new TestException().tt();
}catch(Exception e){
System.out.println("Error handled");
}
}
public void tt() throws Exception {
try {
throw new RuntimeException();
}catch (Exception e) {
throw e;
}
}
}
一般来说,如果你捕捉到一个异常,你就会处理它。像这样
public class TestException {
public static void main(String[] args) {
new TestException().tt();
}
public void tt() {
try {
throw new RuntimeException();
}catch (Exception e) {
System.out.println("Error caught! ")
}
}
}
或者
public class TestException {
public static void main(String[] args) {
try {
new TestException().tt();
}catch(Exception e){
System.out.println("Error caught! ")
}
}
public void tt() throws RuntimeException {
throw new RuntimeException();
}
}
你也可以抛出其他的异常
public class TestException {
public static void main(String[] args) {
try{
new TestException().a();
}catch(Exception e){
System.out.println("Error handled");
}
}
public void a() throws Exception {
b();
}
public void b() throws Exception {
c();
}
public void c() throws Exception {
throw new RuntimeException();
}
}
推荐阅读
- devops - Prometheus Opsgenie 集成
- c# - 您好,我遇到了 uinty Andriod ANR 崩溃的新问题
- yaml - 如何在 GItLab CI/CD YAML 值中使用以下空格转义冒号?
- javascript - 如何在 JavaScript 中删除对象?
- javascript - 运行 webpack 后,其中一个 dist 文件始终为空
- serial-port - QEMU 串行标准输出在 archlinux 客户机上发散
- java - 如何将 id 放入重定向(@PutMapping)
- javascript - 检查 Firestore 数据库布尔返回值
- node.js - bad auth:身份验证失败
- javascript - 嵌套循环没有得到预期的结果