Wol*_*gon 41 java exception throwable
鉴于:Throwable
是Exception
超级.
当我编写自己的"例外"读课文,我看到的例子Throwable
中所使用catch
的块和其他经文显示new Exception()
在正在使用catch
块.我还没有看到何时应该使用每个的解释.
我的问题是,什么时候应该Throwable
使用,什么时候应该new Exception()
使用?
使用以下任一内部catch
或else
块内:
throw throwable;
Run Code Online (Sandbox Code Playgroud)
要么
throw new Exception();
Run Code Online (Sandbox Code Playgroud)
Ray*_*yat 38
总是抛出Exception
(永远不会Throwable
).你通常也不会抓到Throwable
,但你可以.Throwable的是超类中Exception
和Error
,所以你会赶上Throwable
如果你想不仅捕捉Exception
秒,但Error
S,这就是点有它.事情是,Error
s通常是普通应用程序不会也不应该捕获的东西,所以只要使用,Exception
除非您有特定的理由使用Throwable
.
Zac*_*ena 14
(来自评论)提出这个问题的一个问题是,如果集合没有构建,我需要将一个"例外"传递给同事正在构建的一段代码.
在这种情况下,您可能希望抛出已检查的异常.你可以抛出一个Exception
适当的现有子类(除了RuntimeException
它的子类以及未经检查的子类),或者自定义的子类Exception
(例如" CollectionBuildException
").请参阅Java Tutorial on Exceptions以快速了解Java异常.
您不应该真正捕获异常并抛出一个新的常规"新异常".
相反,如果您想冒泡出现异常,请执行以下操作:
try {
// Do some stuff here
}
catch (DivideByZeroException e) {
System.out.println("Can't divide by Zero!");
}
catch (IndexOutOfRangeException e) {
// catch the exception
System.out.println("No matching element found.");
}
catch (Throwable e) {
throw e; // rethrow the exception/error that occurred
}
Run Code Online (Sandbox Code Playgroud)
我相信,捕获异常并抛出一个新的异常而不是引发到代码块的异常是不好的做法,除非你提出一个有用的自定义异常,提供足够的上下文来避免原始异常的原因.
小智 5
只有两个地方你应该Throwable
在代码中看到这个词:
public static void main(String args[])
{
try
{
// Do some stuff
}
catch(Throwable t)
{
}
}
Run Code Online (Sandbox Code Playgroud)
和
public class SomeServlet extends HttpServlet
{
public void doPost(HttpRequest request, HttpResponse response)
{
try
{
// Do some stuff
}
catch (Throwable t)
{
// Log
}
}
}
Run Code Online (Sandbox Code Playgroud)