Custom Exceptions


Custom Exceptions

If you want to create your own exceptions then it is called as custom exception or user-defined exception. These are used to customize the exceptions as per user requirements. With these exceptions, we can have our own exception and message.

Syntax:

throw new exception;

Custom exceptions allow you to provide characteristics and methods that aren't included in normal Java exceptions. These can hold additional data, such as an application-specific error code, or provide utility methods for handling or presenting the exception to the user.

The following are the primary motivations for implementing custom exceptions:

  • Exceptions about business logic and workflow are known as business logic exceptions. They aid the app users and developers in determining the specific nature of the issue.
  • To catch and treat a subset of current Java exceptions in a certain way.

Essential notes about Java Custom Exceptions:

  • Exceptions defined by the user must extend the Exception class.
  • The throw keyword is used to throw the exception.
  • Throwable must be the parent of all exceptions.
  • You must extend the Exception class if you want to build a checked exception enforced automatically by the Handle or Declare Rule.
  • You must extend the RuntimeException class if you wish to write a runtime exception.

Catch block
Java is a programming language

Example:

Com.knowledge2life class MyCustomException extends Exception { } public class Main { public static void main(String args[]) { try { throw new MyCustomException(); } catch (MyCustomException ex) { System.out.println("Caught the exception"); System.out.println(ex.getMessage()); } System.out.println("rest of the code..."); } }

OUTPUT:

Caught the exception
null
rest of the code...