如何解决Java RuntimeException捕获多个catch块
我有以下代码
`
package com.test.Custom;
public class StreamError
{
public static void main(String[] args)
{
try
{
String str = "Hello";
if (!str.equals("Hello"))
{
throw new RuntimeException("None of the Directories Exists-Message failed");
}
int inf = ster(9);
System.out.print(inf);
}
catch (RuntimeException stex)
{
//getTrace().addWarning("Failing the message");
RuntimeException rme = new RuntimeException("None of the Directories Exists-Message failed",stex);
throw rme;
}
}
public static int ster(int intg)
{ try
{
if (intg >6)
{
throw new RuntimeException("None of the files Exists-Message failed");
}
else
return intg;
}
catch (RuntimeException ste)
{
//getTrace().addWarning("Failing the message");
RuntimeException pme = new RuntimeException("None of the files Exists-Message failed",ste);
throw pme;
}
}
}
`
当我对整数> 6(例如9)执行此操作时,我可以看到它从两个catch块中抛出了运行时异常-即使Directory部分正确,即String str = Hello。
Exception in thread "main" java.lang.RuntimeException: None of the Directories Exists-Message failed
at com.test.Custom.StreamError.main(StreamError.java:21)
Caused by: java.lang.RuntimeException: None of the files Exists-Message failed
at com.test.Custom.StreamError.ster(StreamError.java:39)
at com.test.Custom.StreamError.main(StreamError.java:11)
Caused by: java.lang.RuntimeException: None of the files Exists-Message failed
at com.test.Custom.StreamError.ster(StreamError.java:31)
... 1 more
但是,当我针对错误的目录(例如abcd)和正确的整数(例如2)运行此文件时,它仅返回目录catch块中的运行时异常。
Exception in thread "main" java.lang.RuntimeException: None of the Directories Exists-Message failed
at com.test.Custom.StreamError.main(StreamError.java:22)
Caused by: java.lang.RuntimeException: None of the Directories Exists-Message failed
at com.test.Custom.StreamError.main(StreamError.java:13
) 我缺少一些基本的东西吗?请帮忙。
谢谢 杉田
解决方法
这是因为,即使在第一个try块中字符串是ster (9)
,您仍在调用"Hello"
。因此,在ster(9)
上您有一个异常,但是该异常也会破坏第一个try语句。因此,它同时进入了两个catch语句(第一和第二)。如果您不想要它,可以在try语句之外调用此int inf = ster(9);
。
如果捕获异常只是为了将其进一步抛出,则在第一实例中捕获它就毫无意义。这就是您示例中的问题,不要在catch块中引发异常,而要处理它(记录消息或其他内容)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。