You throw an exception by creating an instance of the exception class and passing it to the throw keyword. For example:
MyException ex = new MyException( "This is my exception" ); throw ex;
throw new MyException( "This is my exception" );
You handle an exception by call any method that can throw an exception in a try block and then catching the exception in a catch block. If the method accelerate() can throw a CarException then you would handle it as follows:
The try keyword denotes the start of a try block; the try block contains method calls that can throw exceptions and it exists to handle those exceptions.
Exceptions that derive from the java.lang.Exception class.
Exceptions that derive from the java.lang.RuntimeException class.
A subclass method can only throw exceptions that are explicitly defined in its super class's method's signature. The only caveat is that it can throw an exception that is of a class type that subclasses one of the super class method's exceptions.
The throws method is used in a method's signature to define the list of exceptions that the method can throw.
These are the steps:
Create a class that extends the java.lang.Exception class.
In a class that will throw this exception, create a method that lists the custom exception in its throws clause.
Somewhere in the method create an instance of the custom exception and throw it using the throw keyword.
Exceptions are classes because they need to be sent from one to another, possibly in a different process. The benefit to you is that you can define your own data and methods in the exception class to help better diagnose the root cause of the problem.