Custom exception for business rule

Custom exception for business rule

Medium Java Exceptions 25 views
Explanation Complexity

Problem Statement

Task: create a custom exception InsufficientBalanceException and throw it when withdraw > balance.

Input Format

An integer balance
An integer withdraw

Output Format

If withdraw > balance → throw InsufficientBalanceException
Else → print remaining balance

Example

100
150
InsufficientBalanceException

Constraints

• balance ≥ 0

• withdraw ≥ 0

• Must create custom exception class

Concept Explanation

If withdrawal amount is greater than balance,
we throw a custom exception instead of allowing negative balance.

Step-by-Step Explanation

1.Create a custom exception class extending Exception.

2.In withdraw method:

• If withdraw > balance, throw new InsufficientBalanceException.

• Else subtract withdraw from balance and return remaining balance.

Concept Explanation

If withdrawal amount is greater than balance,
we throw a custom exception instead of allowing negative balance.

Step-by-Step Explanation

1.Create a custom exception class extending Exception.

2.In withdraw method:

• If withdraw > balance, throw new InsufficientBalanceException.

• Else subtract withdraw from balance and return remaining balance.

Input / Output Format

Input Format
An integer balance
An integer withdraw
Output Format
If withdraw > balance → throw InsufficientBalanceException
Else → print remaining balance
Constraints
• balance ≥ 0

• withdraw ≥ 0

• Must create custom exception class

Examples

Input:
100 150
Output:
InsufficientBalanceException

Example Solution (Public)

Java
static class InsufficientBalanceException extends Exception{}static int withdraw(int bal,int amt) throws InsufficientBalanceException{if(amt>bal) throw new InsufficientBalanceException();return bal-amt;}

Official Solution Code

static class InsufficientBalanceException extends Exception{}static int withdraw(int bal,int amt) throws InsufficientBalanceException{if(amt>bal) throw new InsufficientBalanceException();return bal-amt;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.