当有方法引发异常并且您知道这些异常不会被引发时,您应该怎么办?
很多时候我看到人们只是在记录该异常,但是我想知道java中是否有内置异常,它表示:“不应抛出此异常”。
例如,假设我有一个调用StaticClass.method(someObject)
的代码,并且当SpecificException
无效时,此方法将抛出someObject
。您应该在catch区域做什么?
try {
StaticClass.method(someobject);
} catch (SpecificException e) {
// what should I do here?
}
答案 0 :(得分:1)
如果在调用该方法时确定自己不会因以前的检查而引发异常,则应抛出一个RuntimeException
,并将SpecificException
包装起来。
try {
StaticClass.method(someobject);
} catch (SpecificException e) {
//This is unexpected and should never happen.
throw new RuntimeException("Error occured", e);
}
某些方法在无法实现其目的时已经抛出RuntimeException。
//Here we know for sure that parseInt(..) will not throw an exception so it
//is safe to not catch the RuntimeException.
String s = "1";
int i = Integer.parseInt(s);
//Here instead parseInt(..) will throw a IllegalArgumentException which is a
//RuntimeException because h is not a number. This is something that should
//be fixed in code.
s = "h";
i = Integer.parseInt(s);
RuntimeException不需要try / catch块,并且编译器不会因为不捕获它们而生气。通常,它们会抛出在您的应用程序代码中错误的地方,应予以修复。无论如何,在某些情况下捕获RuntimeException很有用。