Exception Handling in Java

 

Exception Handling in Java

 

In real-world programming, a program may encounter unexpected situations that causes errors and if such errors are not handled properly, the program may crash unexpectedly. To prevent abrupt termination and to allow developers to provide meaningful responses, Java provides a robust exception handling mechanism. Exception handling in Java is a powerful framework that makes programs more reliable, maintainable, and user-friendly.

 

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. In Java, exceptions are objects that describe an error or an unusual condition.

    • Error → Serious problems that a program should not try to handle (e.g., OutOfMemoryError).
    • Exception → Conditions a program can catch and handle (e.g., invalid input, file not found).

Exception Hierarchy

All exceptions are derived from the Throwable class.


Throwable

This is the root class for all exception-related objects in Java and provides the basic framework for error and exception handling.


Error

Errors represent serious and irrecoverable issues that occur in the JVM, such as memory overflow or system crashes, and they cannot be handled by the programmer.


Exception

An exception represents an abnormal condition that occurs during the execution of a program, and it can be caught and handled by the programmer. It is mainly used to ensure smooth program execution.


Checked Exceptions (Compile time Exception):

These are exceptions that occur at compile time, and the compiler ensures that the programmer handles them properly either by using a try-catch block or by declaring them with the throws keyword. Examples include IOException, SQLException


Unchecked Exceptions (Runtime Exception):

These are exceptions that arise during the execution of the program and are not checked by the compiler. They usually result from programming errors such as invalid operations, incorrect logic, or misuse of data. Examples include ArithmeticException, ArrayIndexOutOfBoundsException.

 

// Example Program – Exception Handling in Java

// Keywords: try, catch, throw, throws and finally,

// Built - in and user-defined exceptions

 

import java.io.*;

import java.util.*;

 

// User-defined exception class

class InvalidAgeException extends Exception

{

    // Constructor accepts a message and passes it to the superclass Exception

    public InvalidAgeException(String message)

    {

         super(message);

    }

}

  

// Class for age validation

class AgeValidation

{

    // Method that validates age

    // 'throws' declares that this method might throw InvalidAgeException

    public void validateAge(int age) throws InvalidAgeException

    {

         // 'throw' is used to explicitly create and throw an exception object

         if (age < 0)

         {

throw new InvalidAgeException("Invalid age value. Age cannot be negative.");

        }

        // If age is valid, print the message

        System.out.println(age + " - Valid age.");

    }

}

 

// Main class

public class ExceptionHandling

{

    public static void main(String[] args)

    {

         int age;

         AgeValidation av = new AgeValidation();           // Create AgeValidation object

         Scanner sc = new Scanner(System.in);                // Scanner for user input

 

         try

         {

             // Input from user

             System.out.print("Enter Age : ");

             age = sc.nextInt();

 

             // Validate the input age

             av.validateAge(age);

         }

         // Catch block for user-defined exception

         catch (InvalidAgeException e)

         {

             System.out.println("Caught Exception: " + e.getMessage());

         }

        // Catch block for Built-in Exception

        catch(InputMismatchException e)

        {

             System.out.println("Built-in Exception: " + e);

         }

         // Catch block for other general exceptions

         catch (Exception e)

         {

             System.out.println("General Exception: " + e);

        }

        // The finally block always executes, whether exception occurs or not

         finally

         {

             System.out.println("End of Program.");

        }

    }

}

 

Sample output:

>javac ExceptionHandling.java

 

>java ExceptionHandling

Enter Age : 23

23 - Valid age.

End of Program.

 

>java ExceptionHandling

Enter Age : -5

Caught Exception: Invalid age value. Age cannot be negative.

End of Program.

 

>java ExceptionHandling

Enter Age : qw

Built-in Exception: java.util.InputMismatchException

End of Program.

 


This Java program demonstrates exception handling using the keywords try, catch, throw, throws, and finally. It also shows both built-in and user-defined exceptions.

§  throw → explicitly throws an exception object.

§  throws → declares that a method may throw an exception.

§  try-catch → handles exceptions to prevent abnormal termination.

§  finally → executes regardless of whether an exception occurs.

§  User-defined exception (InvalidAgeException) → demonstrates how to create custom error conditions.

o  A custom exception class is created by extending the Exception class.

o  It is thrown when the entered age is negative.

§  Built-in exception → shows how Java automatically throws exceptions for invalid input.

 

1.   AgeValidation Class

o  Contains the method validateAge(int age) which checks if the age is valid.

o  If age < 0 → it uses throw to raise InvalidAgeException.

o  If age is valid → it prints "Valid age".

o  The method declares throws InvalidAgeException because it might throw this custom exception.

2.   Main Program (ExceptionHandling class)

o  Takes age input from the user using Scanner.

o  Uses a try block to execute code that might cause exceptions.

o  Handles exceptions using multiple catch blocks:

§  User-defined exception → when age is negative.

§  Built-in exception (InputMismatchException) → when input is not a number.

§  General exception → handles any other errors.

o  The finally block executes always, printing "End of Program."

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu