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 the normal flow of the program 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 checking the code before it being used. Syntax of Java throwsWhich exception should be declared?Ans: 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. Testthrows1.java Test it NowOutput: exception handled normal flow... Rule: If we are calling a method that declares an exception, we must either caught or declare the exception.There are two cases:
Case 1: Handle Exception Using try-catch blockIn case we handle the exception, the code will be executed fine whether exception occurs during the program or not. Testthrows2.java Test it NowOutput: exception handled normal flow... Case 2: Declare Exception
Let's see examples for both the scenario. A) If exception does not occur Testthrows3.java Test it NowOutput: device operation performed normal flow... B) If exception occurs Testthrows4.java Test it NowOutput: 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 |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India