Arithmetic Exception Handling

I created my own exception to handle situations such as arithmetic exceptions, and other situations involving mathematical rules. But when I call it, it never comes to my Exception, for example, when dividing by zero instead of arithmetic exception instead

+4
source share
3 answers

Division by zero and other "standard" arithmetic errors are handled by the runtime or library of classes that are not aware of your custom exception. You can use your own exceptions only in your own code, briefly throw using them when appropriate.

Of course, you can catch any arithmetic exceptions thrown by the class library and wrap them in your own exceptions:

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

You will 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, adding new exceptions is not recommended unless you add additional information.

+4
source

yes, because exceptions are thrown by jdk source code, not you. If you want to make some kind of custom logic, you can change your own exception in your catch DiviedByZeroException

0
source

All Articles