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.sks.exceptions;

import java.util.Scanner;

public class StudentExceptionTest {

    public static void checkResult(int marks) throws StudentFailedException{
        if(marks < 35)
            throw new StudentFailedException("You failed because you scored less than 35.");
        else
            System.out.println("Congratulations! You cleared the exam");
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter your marks");

        int marks = sc.nextInt();

        try {
            checkResult(marks);
        } catch (StudentFailedException e) {
            System.out.println(e.getExceptionMsg());
        }

        sc.close();
    }

}
Output :
Student failed because he has scored less than 35.
com.sks.StudentFailedException
	at com.sks.CustomExceptionExample.main(CustomExceptionExample.java:12)