In Java, you can override the message of an exception by defining a custom exception class that extends an existing exception class and includes a constructor that sets the message of the exception.
Here's an example of how to override the message of an exception in Java:
public class CustomException extends Exception { public CustomException(String message) { super(message); } }
In this example, a custom exception class called CustomException
is defined that extends the Exception
class. The CustomException
class includes a constructor that takes a String
argument and passes it to the super
class's constructor using the super
keyword.
To use the CustomException
class, you can throw an instance of it using the throw
statement and pass in a custom message as an argument to the constructor.
try { // code that may throw an exception throw new CustomException("Custom exception message"); } catch (CustomException ex) { System.out.println(ex.getMessage()); }
In this example, an instance of the CustomException
class is thrown with a custom message. The CustomException
is caught in the catch
block and the exception's message is printed using the getMessage()
method.
You can use this technique to override the message of any exception in Java by defining a custom exception class that extends the exception class you want to override and includes a constructor that sets the message of the exception.