45. How to make your own custom exception?

How to make your own custom exception?

 

In Java, you can easily create your own custom exception class which is extends from Exception class
If you want to create your own custom runtime exception class, you can extend from RuntimeException class.

Example:

// Custom unchecked exception
class CustomUncheckedException extends RuntimeException {
public CustomUncheckedException(String message) {
super(message);
}
}

// Class using the custom unchecked exception
public class CustomUncheckedExceptionExample {
public static void main(String[] args) {
try {
throwCustomUncheckedException();
} catch (CustomUncheckedException e) {
System.out.println(“Caught CustomUncheckedException: ” + e.getMessage());
}
}

public static void throwCustomUncheckedException() {
throw new CustomUncheckedException(“This is a custom unchecked exception.”);
}
}

Leave a Reply

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