假设我有一个try
- finally
块没有catch块,我们在try
块内抛出一个异常。我能抓住那个例外吗?我们可以捕捉一个没有catch块的异常吗?
public static void main(String[] args) throws IOException{
try {
throw new IOException("Something went wrong");
} finally{
}
}
假设我有一个try
- finally
块没有catch块,我们在try
块内抛出一个异常。我能抓住那个例外吗?我们可以捕捉一个没有catch块的异常吗?
public static void main(String[] args) throws IOException{
try {
throw new IOException("Something went wrong");
} finally{
}
}
是的,这是可能的。
您可以使用未捕获的异常处理程序。它的责任是捕捉你的程序没有捕捉到的异常,并用它做一些事情。
public static void main(String[] args) throws IOException {
Thread.setDefaultUncaughtExceptionHandler((thread, thr) -> thr.printStackTrace());
throw new IOException("Something went wrong");
}
setDefaultUncaughtExceptionHandler
是将注册时的例外在任何线程中被抛出,并没有抓到会被调用处理程序的方法。上面的代码将打印throwable句柄的堆栈跟踪。
处理程序将异常发生的线程和抛出的throwable作为参数。
您还可以通过在Thread
实例上使用setUncaughtExceptionHandler
,为每个线程设置处理程序。该处理程序将处理从此线程抛出的所有未捕获的异常。
从来没有听说过它,但它的作品。 – SHE
您在那里的代码不会编译。但是,您可以通过添加“catch”块来捕获异常。 – Dando18
如果你想捕获一个异常,那么使用catch类。 –
这个问题没有任何意义:) –