Java – Custom Exceptions

Custom Exceptions:

  • Defining a class by extending from Exception is called Custom Exception.
  • Examples:
    • InvalidAgeException
    • LowBalanceException

Defining Custom Exception:

class MyException extends Exception
{
            // body;
}

throw:

  • Pre-defined exceptions automatically raised when error occurred.
  • Custom exceptions must be raised manually by the programmer using throw-keyword.
LowBalanceException obj = new LowBalanceException(“Low Balance in Account”);
          throw obj;

throws:

  • ‘throws’ is used to describe the exception which may raise in Method logic.
  • Prototype of method specifies the Exception type.
  • We handle that exception when we invoke the method.

String to int conversion:

  • parseInt() is a pre-defined method that converts String to int
  • parseInt() raises Exception if the input is non-convertible integer.

Pre-defined Method as follows:

class Integer
{
	public static int parseInt(String s) throws NumberFormatException
	{
		logic;
	}
}

Method-1: we can handle using try-catch while using method.

static void main()
{
	String s = "abc";
	try{
		int x = Integer.parseInt(s);
	}
	catch(NumberFormatException e){
		System.out.println("Invalid string");
	}
}

Method-2: throws the same exception without handling

static void main() throws NumberFormatException
{
	String s = "abc";
	int x = Integer.parseInt(s);
}

InvalidAgeException:

import java.util.Scanner;
class InvalidAgeException extends Exception
{
            InvalidAgeException(String name){
                        super(name);
            }
}
 
class Person
{
            static void canVote(int age) throws InvalidAgeException{
                        if(age>=18){
                                    System.out.println(“Can vote”);
                        }
                        else{
                                    InvalidAgeException obj = new InvalidAgeException(“Invalid Age”);
                                    throw obj;
                        }
            }
}
 
class Main
{
            public static void main(String[] args){
                        System.out.print(“Enter age : “);
                        Scanner sc = new Scanner(System.in);
                        int age = sc.nextInt();
                        try{
                                    Person.canVote(age);
                        }
                        catch (InvalidAgeException e){
                                    System.out.println(“Exception : ” + e.getMessage());
                        }
            }
}

LowBalanceException:

import java.util.Scanner;
class LowBalanceException extends Exception
{
            LowBalanceException(String name) {
                        super(name);
            }
}
class Account
{
            int balance;
            Account(int balance) {
                        this.balance = balance;
            }
 
            void withdraw(int amount) throws LowBalanceException {
                        if(amount <= this.balance) {
                                    System.out.println(“Collect cash : ” + amount);
                                    this.balance = this.balance – amount;
                        }
                        else {
                                    LowBalanceException obj = new LowBalanceException(“Low balance”);
                                    throw obj;
                        }
            }
}
 
class Bank
{
            public static void main(String[] args) {
                        Scanner sc = new Scanner(System.in);
                        System.out.print(“Enter initial balance : “);
                        int amount = sc.nextInt();
 
                        Account acc = new Account(amount);
                        System.out.println(“Account created with balance : ” + acc.balance);
 
                        System.out.print(“Enter withdraw amount : “);
                        amount = sc.nextInt();
 
                        try {
                                    acc.withdraw(amount);
                        }
                        catch (LowBalanceException e) {
                                    System.out.println(“Exception : ” + e.getMessage());
                        }
                        System.out.println(“Final balance : ” + acc.balance);
            }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top