Java 如何处理您没有处理的异常';我甚至没想到文档上已经声明了?

Java 如何处理您没有处理的异常';我甚至没想到文档上已经声明了?,java,exception,code-design,Java,Exception,Code Design,当存在抛出异常的方法,并且您知道这些异常不会被抛出时,您应该怎么做 很多时候,我看到人们只是记录异常,但我想知道java中是否有一个内置异常,它的意思是:“不应该抛出这个异常” 例如,假设我有一个调用StaticClass.method(someObject)的代码,当someObject无效时,该方法抛出一个specificeexception。你应该在接球区做什么 try { StaticClass.method(someobject); } catch (SpecificExcepti

当存在抛出异常的方法,并且您知道这些异常不会被抛出时,您应该怎么做

很多时候,我看到人们只是记录异常,但我想知道java中是否有一个内置异常,它的意思是:“不应该抛出这个异常”

例如,假设我有一个调用
StaticClass.method(someObject)
的代码,当
someObject
无效时,该方法抛出一个
specificeexception
。你应该在接球区做什么

try {
  StaticClass.method(someobject);
} catch (SpecificException e) {
  // what should I do here?
}

如果在调用该方法时,您确信它不会因为之前的检查而引发异常,那么应该引发一个
RuntimeException
来包装
specificeexception

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);

运行时异常不需要try/catch块,编译器也不会因为没有捕捉到它们而生气。通常,当你的应用程序代码中有错误并且应该修复时,就会抛出它们。无论如何,在某些情况下捕获RuntimeException是有用的。

这完全取决于该异常对程序的重要性。你能正常继续吗?还是干脆退出更好?干脆退出更好