Java throws keywordThe 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 throwsWhich exception should be declaredAns) checked exception only, because:
Advantage of Java throws keywordNow Checked Exception can be propagated (forwarded in call stack). It provides information to the caller of the method about the exception. Java throws exampleLet's see the example of java throws clause which describes that checked exceptions can be propagated by throws keyword. Test it NowOutput: exception handled normal flow... Rule: If you are calling a method that declares an exception, you must either caught or declare the exception.
Case1: You handle the exception
Output:exception handled normal flow... Case2: You declare the exception
Output:device operation performed normal flow... B)Program if exception occurs Test it Now Output:Runtime Exception Difference between throw and throwsClick me for detailsQue) Can we rethrow an exception?Yes, by throwing same exception in catch block.
Next TopicThrow vs Throws
|