[英]How to catch all exceptions except a specific one?
Is it possible to catch all exceptions of a method, except for a specific one, which should be thrown?除了应该抛出的特定异常之外,是否可以捕获方法的所有异常?
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException) {
//can I throw this to the next level without eating it up in the last catch block?
} catch (Exception e) {
//default routine for all other exceptions
}
}
/Sidenote: the marked "duplicate" has nothing to do with my question! /旁注:标记的“重复”与我的问题无关!
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException se) {
throw se;
} catch (Exception e) {
//default routine for all other exceptions
}
}
you can do like this你可以这样做
try {
methodThrowingDifferentExceptions();
} catch (Exception e) {
if(e instanceof SpecificException){
throw e;
}
}
While other answers are correct, they do not keep the original stack trace. 尽管其他答案是正确的,但它们不会保留原始堆栈跟踪。 You can use something like this instead: 您可以改用以下方式:
try
{
// This throws
DoSomething();
}
catch(MyException exc)
{
// This will let the original exception re-throw while keeping it's stack trace
ExceptionDispatchInfo.Capture(exc).Throw();
// This will never be called, but is necessary so the compiler does not complain
// about the fact that the method must return something in every path
throw;
}
catch(Exception exc)
{
// This will only be called for other types
throw new MoreSpecificException("Oops", exc);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.