Is there any kind of Java exception that serves as a boilerplate basic exception, where…
- User
Is there any kind of Java exception that serves as a boilerplate basic exception, where I can provide to it a message and that's it?
- Assistant
Yes, you can use the
RuntimeExceptionclass in Java to create a basic exception with a custom message.Here's an example of how to create and throw a basic exception with a message:
public class ExampleException extends RuntimeException { public ExampleException(String message) { super(message); } } public class Main { public static void main(String[] args) { try { // Throw the custom exception with a message throw new ExampleException("Custom exception message"); } catch (ExampleException ex) { // Print the exception message System.out.println(ex.getMessage()); } } }In this example,
ExampleExceptionextends theRuntimeExceptionclass, which is an unchecked exception. The constructor ofExampleExceptionaccepts a message and passes it to the constructor of the superclass (RuntimeException).By throwing an instance of
ExampleException, you can provide a custom message that will be displayed when catching the exception.Note that you can customize and extend the exception class according to your requirements.