Throw & Throws in Java | Exception Handling – Part 3
In this java programming tutorial post, we will study and understand the working of throw and throws keyword which helps in performing exception handling in java. Before we start of with this topic, you can checkout the Part 1 of Exception handling where we discussed the overall concept of Exception handling and how it works in Java. Click here to go the article.
Java Exception Handling Keywords –
There are 5 keywords used in java exception handling.
- try (click here to check this article)
- catch (click here to check this article)
- finally (click here to check this article)
- throw
- throws
Java Exception propagation
An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method,If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.This is called exception propagation.
class TestExceptionPropagation1{ void m(){ int data=50/0; } void n(){ m(); } void p(){ try{ n(); }catch(Exception e){System.out.println("exception handled");} } public static void main(String args[]){ TestExceptionPropagation1 obj=new TestExceptionPropagation1(); obj.p(); System.out.println("normal flow..."); } }
Output –
Output:exception handled normal flow...
Java throw keyword
The Java throw keyword is used to explicitly throw an exception. We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception(we will study about them in further tutorials)
The syntax of java throw keyword is given below.