在Java中声明自定义异常 [英] Declaring custom exception in Java
问题描述
当我尝试捕获这个异常时,它给我一个编译错误消息,表示异常LinkedListException从不抛出在相应的try语句的正文中。这是什么意思?
try {
/ pre>
LList.Node someNode = list.nextNode(node);
//我们不应该到这里。
assertTrue(false);
}
catch(LinkedListException ex){
//如果我们到达这里,我们很高兴抛出异常
}
解决方案异常必须在代码中的某个地方使用
throw
关键字。
例如,
ArithmeticException
在代码中抛出一些深处。如果你不想处理(就像人们想要写的ArithmeticException
),你可以像void someMethod()throws Exception
{
throw new Exception();
}
调用此方法的人必须使用
尝试
,catch
,finally
像我们通常做的例外throw new LinkedListException() / code>某些你试图阻止你想要提出异常的地方。
when I try to catch this exception it gives me a compilation error message that says, "exception LinkedListException is never thrown in body of corresponding try statement". What does this mean?
try { LList.Node someNode = list.nextNode(node); // We should not get here. assertTrue(false); } catch ( LinkedListException ex) { // If we get here we are happy as it throw the exception }
解决方案The exception must be thrown somewhere in your code using
throw
keyword.For example,
The
ArithmeticException
is thrown some where deep inside the code . If you don't want to handle( just like how the person thought about writingArithmeticException
) you can bubble up likevoid someMethod () throws Exception { throw new Exception(); }
The person who called this method have to handle it with
try
,catch
,finally
like we usually do for exceptionsIOException
etc.So, if you want to throw your exception, add this
throw new LinkedListException()
some where in your try block where ever you want to raise an exception.这篇关于在Java中声明自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!