Advanced Java Programming - Old Questions

2. Why do we need to handle the exception? Distinguish error and exception, Write a program to demonstrate your own exception class. [1+2+7]

10 marks | Asked in 2075

An exception is an event that occurs during the execution of a program and that disrupts the normal flow of instructions. Java exceptions are specialized events that indicate something bad has happened in the application, and the application either needs to recover or exit.

Exception handling is important because it helps maintain the normal, desired flow of the program even when unexpected events occur. If Java exceptions are not handled, programs may crash or requests may fail. Suppose there are 10 statements in a program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling

Error vs Exception

ErrorException
An error is caused due to lack of system resources.
An exception is caused because of the code.
An error is irrecoverable.
An exception is recoverable.
There is no means to handle an error by the program code.
Exceptions are handled using three keywords "try", "catch", and "throw".
It belongs to java.lang.error 
It belongs to java.lang.Exception 
As the error is detected the program will terminated abnormally.
As an exception is detected, it is thrown and caught by the "throw" and "catch" keywords correspondingly.
Errors are classified as unchecked type.
Exceptions are classified as checked or unchecked type.
E.g. Java.lang.StackOverFlow,  java.lang.OutOfMemoryErrorE.g.  SQLException, IOException, ArrayIndexOutOfBoundException

In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Using the custom exception, we can have your own exception and message. Here, we have passed a string to the constructor of superclass i.e. Exception class that can be obtained using getMessage() method on the object we have created.

Example:

class CustomException extends Exception {
   String message;
   CustomException(String str) {
      message = str;
   }
   public String toString() {
      return ("Custom Exception Occurred : " + message);
   }
}
public class MainException {
   public static void main(String args[]) {
      try {
         throw new CustomException("This is a custom message");
      } catch(CustomException e) {
         System.out.println(e);
      }
   }
}