Custom Exception Java Program

Hello everyone, Here I have shared my knowledge of How Create Custom Exception Java Program Example. The program has been tested and output is attached in the same post.

Customer

package com.javatraineronline;
public class Customer {
private int customerId;
private String customerName;
private int customerAge;
public Customer(int customerId, String customerName, int customerAge) {
this.customerId = customerId;
this.customerName = customerName;
this.customerAge = customerAge;
}
public int getCustomerId() {
return customerId;
}
public String getCustomerName() {
return customerName;
}
public int getCustomerAge() {
return customerAge;
}
}

CustomerException.java

package com.javatraineronline;
public class CustomerException extends Exception {
private String message;
public CustomerException(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}

CustomerService.java

package com.javatraineronline;
public class CustomerService {
public void addCustomer(Customer customer) throws CustomerException {
// Performing the validation before Inserting to DB
if(customer == null) { // Validation 1
throw new NullPointerException(); // Predefined Exception 
}
if(customer.getCustomerId() <= 0) { // Validation 2
throw new CustomerException("Invalid Customer ID"); // Custom Exception
}
if(customer.getCustomerAge() <= 0) { // Validation 3
throw new CustomerException("Invalid Customer Age"); // Custom Exception
}
// All other exception you can include based on the business requirement.
// Database Operation goes here...
// Printing Success message if no exception
System.out.println("Hi "+customer.getCustomerName()+" your information added successfully !!!");
}
}

CustomerApplication.java

package com.javatraineronline;
public class CustomerApplication {
public static void main(String[] args) {
CustomerService service = new CustomerService();
Customer customer1 = new Customer(1001, "John", 30);
Customer customer2 = new Customer(1002, "Smith", -35);
try {
System.out.println("Processing... customer1 object");
System.out.println("-------------------------------");
// Processing the customer1 object
service.addCustomer(customer1);
System.out.println();
System.out.println("Processing... customer2 object");
System.out.println("-------------------------------");
// Processing the customer2 object
service.addCustomer(customer2);
} catch (CustomerException e) {
System.out.println(e.getMessage());
}
}
}

Output

[su_box title=”Output for CustomerApplication.java”]Processing… customer1 object
——————————-
Hi John your information added successfully !!!

Processing… customer2 object
——————————-
Invalid Customer Age
[/su_box]

Tags:

No responses yet

Leave a Reply

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