throw and throws (1)
throw and throws (1)
In Java, Exception Handling is one of the effective means to handle runtime errors so that
the regular flow of the application can be preserved. Java Exception Handling is a
mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
In this article, we will learn about throw and throws in Java which can handle exceptions in Java.
Java throw
The throw keyword in Java is used to explicitly throw an exception from a method or any
block of code. We can throw either checked or unchecked exception. The throw keyword is
mainly used to throw custom exceptions.
Example:
throw new ArithmeticException("/ by zero");
But this exception i.e., Instance must be of type Throwable or a subclass of Throwable.
The flow of execution of the program stops immediately after the throw statement is
executed and the nearest enclosing try block is checked to see if it has a catch statement
that matches the type of exception. If it finds a match, controlled is transferred to that
statement otherwise next enclosing try block is checked, and so on. If no matching catch is
found then the default exception handler will halt the program.
Java throws
throws is a keyword in Java that is used in the signature of a method to indicate that this
method might throw one of the listed type exceptions. The caller to these methods has to
handle the exception using a try-catch block.
In a program, if there is a chance of raising an exception then the compiler always warns
us about it and compulsorily we should handle that checked exception, Otherwise, we
will get compile time error saying unreported exception XXX must be caught or
declared to be thrown. To prevent this compile time error we can handle the exception
in two ways:
Output
error: unreported exception InterruptedException; must be caught or
declared to be thrown
Explanation
In the above program, we are getting compile time error because there is a chance of
exception if the main thread is going to sleep, other threads get the chance to execute
the main() method which will cause InterruptedException .
Key
S.N. Difference throw throws
The throw keyword is used inside a The throws keyword is used in the
Point of function. It is used when it is function signature. It is used when the
1.
Usage required to throw an Exception function has some statements that can
logically. lead to exceptions.