Practical-44
Write a java program which shows throwing our own Exception.
Introdution
Writing a program that throws an exception can be done simply in Java. Exceptions provide an effective way of dealing with errors that occur within a program. Exceptions are objects and can be created and thrown in Java by using the keyword 'throw'. This can be done intentionally, when a certain condition in the code is not met, or it can be done by the Java Virtual Machine (JVM). When an exception is thrown, the program stops executing and control is transferred to the exception handler.
Code
try{
System.out.println(1/0);
}
catch(ArithmeticException ex){
System.out.println("You can not divide a number by zero");
throw ex;
}
Output
You can not divide a number by zero
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ....
The above code throws an ArithmeticException when an attempt is made to divide an integer by 0. The 'try-catch' block is used to try to execute some code and if the code throws an exception, the exception is caught in the 'catch' block. In this example, the same exception is then thrown again by the 'throw' keyword and the stack trace is printed.