Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.
Syntax of java throws
Which exception should be declared
Ans) checked exception only, because:
- unchecked Exception: under your control so correct your code.
- error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
Java throws example
Let's see the example of java throws clause which describes that checked exceptions can be propagated by throws keyword.
Output:
exception handled normal flow...
Rule: If you are calling a method that declares an exception, you must either caught or declare the exception.
There are two cases:
|
Case1: You handle the exception
- In case you handle the exception, the code will be executed fine whether exception occurs during the program or not.
Output:exception handled
normal flow...
Case2: You declare the exception
- A)In case you declare the exception, if exception does not occur, the code will be executed fine.
- B)In case you declare the exception if exception occures, an exception will be thrown at runtime because throws does not handle the exception.
Output:device operation performed
normal flow...
B)Program if exception occurs
Output:Runtime Exception
Que) Can we rethrow an exception?
Yes, by throwing same exception in catch block.
gud
ReplyDelete