java try catch / Chapter 4 / Exception Handling

java try catch


java try catch block is highly recommended to handle exceptions.

The code which may rise an exception is called risky code and we have to define that code inside try block and corresponding handling code we have to define inside catch block.
try 
{
Risky Code
}
catch (Exception e)
{
Exception Handling code
}

let's take an example of a java program without try catch
class Test
{
public static void main(String [] args)
{
System.out.println("First Hello");
System.out.println(10/0);
System.out.println("Second Hello");
}
}

    First Hello
RuntimeException : ArithmaticException / by zero

let's take another example of a java program with try catch
class Test
{
public static void main(String [] args)
{
System.out.println("First Hello");
try
{
System.out.println(10/0);
}
catch(ArithmeticException e )
{
System.out.println(10/0);
}
System.out.println("Second Hello");
}
}

  First Hello
5
Second Hello

 Control Flow in java try catch block


   try 
{
Statement 1;
Statement 2;
Statement 3;
}
catch( Exception e)
{
Statement 4;
}
Statement 5;


case 1:


If there is no exception then the control flow of the program

Statement 1⇒⇒Statement 2⇒⇒Statement 3⇒⇒Statement 5

case 2:


If there is an exception raised at Statement 2 and corresponding catch block matched then the control flow of the program.

Statement 1⇒⇒Statement 4⇒⇒Statement 5 (Normal Termination)

case 3:


If there is an exception raised at  Statement 2 and corresponding catch block is not matched then the control flow of the program.

Statement 1⇒⇒ (Abnormal Termination)

case 4:


If there is an exception raised at  Statement 4 and Statement 5 then it will be always abnormal termination of the program.

(Abnormal Termination)

Note:



  1. Within the try block if anywhere an exception raised then rest of the try block won't be executed even though we have handled that exception hence, within the try block we have to take only risky code and length of the try block should be as less as possible.

  2. In addition, to try block there may be a chance of raising an exception inside the catch and finally block also.

  3. If any statement which is not part of the try block and raises an exception then it is always called abnormal termination of the program.

No comments:

Post a Comment

Be the first to comment!

Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.

Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.

Regards,
JavaByChetan
Back To Home

Flipkart End Of Season Sale






© Copyright 2017 Javabychetan.blogspot.com