Home ProgrammingJava Example Illustrating Exception try catch blocks

Example Illustrating Exception try catch blocks

by Log Raj
445 views

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:

  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.

 

You may also like

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Example Illustrating Exception try catch blocks

by Log Raj time to read: 1 min
0