简体   繁体   English

如果系统抛出已检查的异常,是否可以被默认处理程序捕获?

[英]can checked exceptions, if thrown by system, be caught by the default handler?

Also, does the default handler catches an exception thrown by us?另外,默认处理程序是否捕获了我们抛出的异常? If yes, then does it depend on whether the exception is checked or not?如果是,那么它是否取决于是否检查了异常?

Any Throwable can be caught.任何Throwable都可以被捕获。 But subclasses of Error are not intended to be caught by user application code.但是Error的子类并不打算被用户应用程序代码捕获。 They still can be caught, but some errors may even leave application in bad state ( OutOfMemoryError for example).它们仍然可以被捕获,但一些错误甚至可能使应用程序处于错误的 state 中(例如OutOfMemoryError )。

A catch block will catch any sub-type of the declared Throwable type. catch 块将捕获声明的 Throwable 类型的任何子类型。 For example catch (Exception ex) {} will handle any Exception that is thrown in the try block, as even RuntimeException (un-checked) is a child.例如catch (Exception ex) {}将处理在 try 块中抛出的任何异常,因为即使 RuntimeException(未检查)也是一个孩子。

Note that this will not catch instances of Error, since they are not a sub-class of exception.请注意,这不会捕获 Error 的实例,因为它们不是异常的子类。 If you really want a catch all, you can use something like catch (Throwable th) .如果你真的想要一个全能,你可以使用像catch (Throwable th)这样的东西。 This is not advisable, since Error's, are usually an indication of a problem that the application cannot easily recover from by itself.这是不可取的,因为错误通常表明应用程序无法轻松地自行恢复。

There's a little-known fact about checked/unchecked exceptions: The distinction exists only at compile time.关于已检查/未检查的异常有一个鲜为人知的事实:区别仅存在于编译时。

If, by some ugly trick, you manage to throw a checked exception at a place where it isn't declared to be thrown, then it will be handled just like an unchecked exception (ie it will will fall through as many stack frames as necessary to reach the nearest matching catch block).如果通过一些丑陋的技巧,您设法在未声明要抛出的地方抛出已检查异常,那么它将像未检查异常一样被处理(即它将根据需要通过尽可能多的堆栈帧到达最近的匹配捕获块)。 And yes, such tricks exist.是的,存在这样的技巧。

And if by default handle your mean the Thread default uncaught exception handler (or the per-thread uncaught exception handler ), then yes: they will handle both checked and unchecked exceptions that are not handled by catching them "normally".如果默认处理您的意思是Thread 默认未捕获异常处理程序(或每个线程未捕获异常处理程序),那么是的:它们将处理未通过“正常”捕获它们来处理的已检查和未检查异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM