Exception Handling in Java Programming :
- An exception is an event.
- Exception occurs during the execution of a program when normal flow of the program is Interrupted or disturbed.
- Exception Handling is machanism to handle the exceptions.
How Exception Handling Works in Java ?
- When any error occures in a method then new object (i.e Exception Object) is created by a method
- Exception Object contain information about error such as type of error and state of the program.
- Newly created exception object is passed to the Runtime System.
- Runtime system will handle the exception to keep system stable
Advantages of Exception Handling :
In the previous programming languages, whenever any illegal condition is executed then program flow gets disturbed. In java programming exception handling ensures that program should run smoother. Consider the following example -
public class ExceptionExample { public static void main(String[] args) { int num1 = 50; int num2 = 0; int ans; ans = num1 / num2; System.out.println("Result of Division : " + ans); } }
In this example, we know that any number divided by 0 will cause program to go into unexpected situation. If program contain such unexpected statements then its better to handle these unexpected results. Below is the unexpected error output -
Exception in thread "main" java.lang.ArithmeticException: / by zero at DivideByZeroNoExceptionHandling.main( DivideByZeroNoExceptionHandling.java:7)
Now we have done slight modification in the program by providing exception handling code in the program -
public class ExceptionExample { public static void main(String[] args) { int num1 = 50; int num2 = 0; int ans; try { ans = num1 / num2; System.out.println("Result of Division : " + ans); } catch(ArithmeticException e) { System.out.println("Divide by Zero Error"); } } }
so the output of the above code will be -
Divide by Zero Error
The post Exception Handling in Java Programming appeared first on Learn Java Programming.