在Java中声明自定义异常 [英] Declaring custom exception in Java

查看:191
本文介绍了在Java中声明自定义异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试捕获这个异常时,它给我一个编译错误消息,表示异常LinkedListException从不抛出在相应的try语句的正文中。这是什么意思?

  try {
LList.Node someNode = list.nextNode(node);
//我们不应该到这里。
assertTrue(false);
}
catch(LinkedListException ex){
//如果我们到达这里,我们很高兴抛出异常
}
/ pre>

解决方案

异常必须在代码中的某个地方使用 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 writing ArithmeticException) you can bubble up like

void 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 exceptions IOException 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆