Explain the importance of exception handling with suitable example.
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. So we have to handle exceptions. Exception handling is the ability of a program to intercept run-time errors, take corrective measures, and then continue. Java exception handling enables our Java applications to handle errors sensibly. Exception handling is a very important yet often neglected aspect of writing robust Java applications or components. When an error occurs in a Java program it usually results in an exception being thrown. How we throw, catch and handle these exception matters. There are several ways to do so. Exception handling is important for a program because it signals that some error or exceptional situation has occurred, and that it doesn't make sense to continue the program flow until the exception has been handled.
Advantages of Exception Handling:
● Exception handling allows us to control the normal flow of the program by using exceptiohandling in program.
● It throws on exception whenever a calling method encounters on error providing that the calling method takes care of that error.
● It also gives us the scope of organizing and differentiating between different error types using a separate block of codes.This is done with the help of try catch blocks.
The following program throws an exception whenever the user of the program gives an invalid age. The invalid age condition is age being negative or age greater than 150. If exception has not been handled here, then the user may possibly have provided the wrong input.
class InvalidAgeException extends Exception {
public InvalidAgeException(String msg) {
System.out.println(msg);
}
}
class Person {
private int age;
public void setAge(int age) throws InvalidAgeException {
if (age < 0 || age > 150) {
throw new InvalidAgeException("Invalid Age");
}
this.age = age;
}
}
public class ExceptionHandling {
public static void main(String[] args) {
Person p = new Person();
try {
p.setAge(-20);
} catch (InvalidAgeException e) {
}
}
}
Comments
Post a Comment