在Java / Android中引发自定义异常 [英] Throw custom Exceptions in Java/Android
问题描述
我正在开发一个自定义Exception类,其中具有以下构造函数:
I'm developing a custom Exception class, in which I have the following constructors:
public class UserException extends Exception
{
string message;
public UserException() {
super();
}
public UserException(String message, Throwable cause)
{
super(message, cause);
this.cause = cause;
this.message = message;
}
}
我创建了一个新的自定义异常,如下所示: / p>
And I create a new custom exception like this:
private Camera.PreviewCallback SetPreviewCallBack() throws UserException {
.......
// Something went wrong
throw new UserException("Something failed.", new Throwable(String.valueOf(UserExceptionType.CaptureFailed)));
}
但是当我插入时,抛出新的UserException(。 ..)
告诉我用 try / catch
包围它!!那不是主意,不是吗?我想在需要抛出自定义异常时抛出它们,而不用更多的 try / catch
替代新异常
But when I insert my throw new UserException(...)
it tells me to surround it with try/catch
!! That's not the idea, isn't it? I want to throw custom exceptions when I need them to be thrown, without surronding my new Exceptions
with more try/catch
clauses.
那么,我在做什么错呢?我误会了什么?
So, what I'm doing wrong? What I'm misunderstanding?
推荐答案
除了Eran的答案,您还可以使自定义Exception扩展 RuntimeException
,不需要捕获。
In addition to Eran's answer, you could also make your custom Exception extend RuntimeException
, which does not need to be caught.
这篇关于在Java / Android中引发自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!