Example Illustrating Exception case 1
In this post I’ll discuss some Example illustrating Exception. In first case I will write a small code in which nothing will be done in order to handle exception.
lets look at the code and paste it to your IDE. Observe the output.
package packOne; public class MainWala { public static void main(String[] args) { System.out.println("Hello line"); System.out.println("Lets perform some calculation and result is "+12/0); System.out.println("Good bye line"); } }
Now it is simple program. Here exception will occur at second statement in main method while dividing 12 by 0.
Observe output:
Hello line Exception in thread "main" java.lang.ArithmeticException: / by zero at packOne.MainWala.main(MainWala.java:8)
We can see that last statement is not executed after exception.
Conclusion from case 1:
- If exception arise in the program program terminates at that point.
- Rest of the code will be not executed after exception.
- When exception occurs default exception handler will show a message of above type.
- message contains name of thread, name of exception, message, location at which exception occurs.
Example Illustrating Exception case 2
Edit the above code and make like below. Surround the risky code in try and write exception handling code in catch block.
package packOne; public class MainWala { public static void main(String[] args) { System.out.println("Hello line"); try{ System.out.println("Lets perform some calculation and result is "+12/0); }catch(Exception e){ System.out.println("Sorry Exception occured here "); System.out.println("reason: "+e.getMessage()); } System.out.println("Good bye line"); } }
Here exception prone code is enclosed in try block. And catch block contain exception handling code i.e. code which is executed when exception occurs.
Analyze the output:
Hello line Sorry Exception occured here reason: / by zero Good bye line
conclusions from case 2:
- try block contain exception prone code
- If exception arise inside try block, jvm executes code inside catch block
- Remaining part of the program execute after that.
- We can put custom code to execute at the time of exception in catch block.
- catch block is executed if and only if exception occur.
Now we have more cases we will look them in next post. Comment down for any query and discussion.