Write a program to demonstrate the use of all keywords made for exception handling.
$ javac Program.java
$ java Program
Following source code demonstrates a situation where multiple customers exist with different names & a transaction is taking place.
All keywords made for exception handling i.e. try
, catch
, finally
, throw
, & throws
are used.
import java.lang.System;
// Entry point of the application.
public class Program {
public static void main(String[] args) {
ServiceProvider provider = new ServiceProvider();
try {
Customer customer = provider.getCustomerFromName("Hitesh");
System.out.println("Customer with the name Hitesh is found.");
// Chaining `Exception`s.
try {
customer.withdraw(6000.0);
} catch (NotEnoughBalance e) {
// This exception will be thrown because available balance (`4000.0`) is less
// than required (`6000.0`).
System.out.println(e.getMessage());
}
} catch (CustomerNotFound e) {
// Handle the exception.
e.printStackTrace();
} finally {
System.out.println("Transaction Complete.");
}
}
}
// `Exception` thrown when there is not enough balance in customer's account.
// `extends` `Exception` class from Java.
class NotEnoughBalance extends Exception {
public NotEnoughBalance(String message) {
super(message);
}
}
// `Exception` thrown when a customer with a given name is not found.
// `extends` `Exception` class from Java.
class CustomerNotFound extends Exception {
public CustomerNotFound(String message) {
super(message);
}
}
// A customer class to store customer's name & balance.
//
// `withdraw` method is used to withdraw the amount from the balance.
// If there is no enough balance, then `NotEnoughBalance` is thrown.
class Customer {
private String name;
private double balance;
Customer(String name, double balance) {
this.name = name;
this.balance = balance;
}
public String getName() {
return name;
}
public double getBalance() {
return balance;
}
// `throws` `NotEnoughBalance`.
public void withdraw(double amount) throws NotEnoughBalance {
if (balance < amount) {
// `throw` `NotEnoughBalance` exception if asked amount is more than the
// balance.
throw new NotEnoughBalance(amount + " is more than the balance (" + balance + ")");
}
balance -= amount;
}
}
// A `ServiceProvider` having various customers in `registeredCustomers`.
class ServiceProvider {
// Hardcoding data for the demo.
private Customer[] registeredCustomers = { new Customer("John", 1000.0), new Customer("Hitesh", 4000.0),
new Customer("Mary", 2000.0), new Customer("Peter", 50.0) };
// Gets registered customer with a given name.
// `throws` `CustomerNotFound` if no customer is found with the name.
public Customer getCustomerFromName(String name) throws CustomerNotFound {
for (Customer customer : registeredCustomers) {
if (customer.getName().equals(name)) {
return customer;
}
}
throw new CustomerNotFound("Customer with name " + name + " is not found");
}
}
right-click & select “Open image in new tab” for larger image.