Master java skills

Java custom exceptions

So far, we have seen java api provided exception classes. But we can also create our own custom exception classes. Such exceptions are known as custom exceptions.

Custom exceptions are also known as user-defined exceptions. Custom exceptions can be created by extending any of the Exception classes.

  1. Custom exceptions are created by extending any of the existing Exception classes.
  2. If a custom exception is extended from a runtime exception class like (ArithmeticException), it would be a runtime exception or unchecked exception.
  3. If a custom exception is extended from a checked exception class, it would be a checked or compile time exception.
  4. If a custom exception is extended from Exception class, it would be a checked exception.

Need of custom exceptions

Sometimes, we need business exceptions for our applications rather than already provided java exceptions. In such scenarios, we create custom exceptions.

Example

package com.javatrainingschool;

public class StudentFailedException extends Exception {
	
	private String exceptionMsg;

	public StudentFailedException(String exceptionMsg) {
		super();
		this.exceptionMsg = exceptionMsg;
	}
	
	public String getExceptionMsg() {
		return exceptionMsg;
	}

}
package com.javatrainingschool;

public class CustomExceptionExample {
	
	public static void main(String[] args) {
		
		int studentMarks = 32;
		if(studentMarks < 35) {
			try {
				throw new StudentFailedException("Student failed because he has scored less than 35.");
			} catch (StudentFailedException e) {
				System.out.println(e.getExceptionMsg()); 
				e.printStackTrace();
			}
		}
		else {
			System.out.println("Student is passed with score = " + studentMarks);
		}
	}
}
Output :
Student failed because he has scored less than 35.
com.sks.StudentFailedException
	at com.sks.CustomExceptionExample.main(CustomExceptionExample.java:12)