Exception Handling

 Exception Handling in Java


// 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.");

    }

}

 

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.");

        }

    }

}


No comments:

Post a Comment

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

Anu