开发者

Handling Arithmetic Exceptions

开发者 https://www.devze.com 2023-03-19 05:21 出处:网络
I\'ve created my own exception to handle situations like ari开发者_运维问答thmetic exceptions, and other situation involving mathematic rules. But When I call it never goes to my Exception for example

I've created my own exception to handle situations like ari开发者_运维问答thmetic exceptions, and other situation involving mathematic rules. But When I call it never goes to my Exception for example,on division by zero goes to arithmetic exception instead


Division by zero and other "standard" arithmetic errors are handled by the runtime or the class library, which don't know about your user defined exception. You can only use your own exceptions in your own code by explcitly throwing them when it is appropriate.

Of course, it is possible to catch any arithmetic exceptions thrown by the class library and wrap them into your own exceptions:

try {
  ...
} catch (java.lang.ArithmeticException exc) {
  throw new MyException("An arithmetic error occurred", exc);
}


You would have to catch the standard Java exceptions for these cases, and wrap them in your exception.

try {
   int x = 10/0;
} catch (ArithmeticException ex) {
   throw new MyException("My additional text", ex);
}

In general, it is not a good idea to add new exceptions unless you will also be adding some additional details.


yes, because the exceptions is throwed by jdk's source code, not you. If you want to do some custom logic, you can rethrow your own exception in your catch DiviedByZeroException block

0

精彩评论

暂无评论...
验证码 换一张
取 消