1.

Write a program in Java to create a user defined exception and also show it working means when it throws an exception.

Answer»

Here, you have to explain and write a user-defined exception of your own. This code is just for reference purposes. So, we are going to create an exception called LowBalanceException for a bank. So, whenever a person comes to the bank to create a bank account, the minimum account balance should be 5000. So, if the balance is less than 5000, the exception will be thrown. Let us write the code for the same.

Java Code for User-Defined Exception

public class Main {
public static void main(String[] args) {
Account a1 = new Account(500);
Account a2 = new Account();
a2.setBalance(500);

Account a3 = new Account(10000);

System.out.println("a1 balance = " + a1.getBalance() + " a2 balance = " + a2.getBalance() + " a3 balance = " + a3.getBalance());
}
}

class Account {
private int balance;
Account() {

balance = 5000;
}

Account(int balance) {
try {
if(balance>=5000) {
this.balance = balance;
System.out.println("The account is created and the balance is set to: "+ balance);
} else {
this.balance=0;
System.out.println("Account can not be created");
throw new LowBalanceException();
}
} catch(LowBalanceException e) {
System.out.println(e);
}

}

void setBalance(int balance) {
try {
if(balance>=5000) {
this.balance = balance;
System.out.println("The account is created and the balance is set to: "+ balance);
} else {
this.balance=0;
System.out.println("Account can not be created");
throw new LowBalanceException();
}

} catch(LowBalanceException e) {
System.out.println(e);
}
}

int getBalance() {
return balance;
}
}
class LowBalanceException extends Exception {

public String toString() {
return "Low Balance: The balance cannot be less than Rs.5000/-";
}

Output

The account can not be created
Low Balance: The balance cannot be less than Rs.5000/-
The account can not be created
Low Balance: The balance cannot be less than Rs.5000/-
The account is created and the balance is set to 10000
a1 balance = 0 a2 balance = 0 a3 balance =10000


Discussion

No Comment Found