Example Illustrating Exception try catch blocks

898 views 3 minutes read
A+A-
Reset

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.

Example Illustrating Exception try catch blocks 2

lets look at the code and paste it to your IDE. Observe the output.

You Might Be Interested In
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:

  1. If exception arise in the program program terminates at that point.
  2. Rest of the code will be not executed after exception.
  3. When exception occurs default exception handler will show a message of above type.
  4. message contains name of thread, name of exception, message, location at which exception occurs.

Example Illustrating Exception case 2

Exception_Handled

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:

  1. try block contain exception prone code
  2. If exception arise inside try block, jvm executes code inside catch block
  3. Remaining part of the program execute after that.
  4. We can put custom code to execute at the time of exception in catch block.
  5. 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.

 

Related Posts

Leave a Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Index

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.