Home > DeveloperSection > Blogs > How to Handle Exception in java

How to Handle Exception in java


Exception Handling Java  Exception  Error 
Ratings:
0 Comment(s)
 666  View(s)
Rate this:

How to Handle Exception in java

Hi everyone in this blog I’m explaining about how to handle exception.

Java try-catch:

Try block is used to enclose the code that might throw exception. It must be used within method. Try block must be followed by either catch or finally block.

Syntax of try-catch:

try
{

      //Code that may throw exception
}

catch(Exception_Class_Name ref){}

Syntax of try-finally:

try
{
            //Code that may throw exception

}
finally
{

          //code that you want to execute in any condition
}

 

Java catch block:

Java catch block is used to handle the exception. It must be used after try block only. You can use multiple catch block with a single try block.

Problem without use exception handling:

class Sample
{
      public static void main(String … s)
     {
            
int d=10;
           
 int r=d/0;
          
 System.out.println(“Rest of the code….”);
  
}
}

Output:

Exception in thread main java.lang.ArithmeticException:/by zero

 

Solution by use exception handling:

class Sample

{

            public static void main(String … s)

            {

                        Try

                        {

                                    int d=10;

                                    int r=d/0;

}

Catch(ArithmeticException ex)

{

                                    System.out.println(“Rest of the code….”);

                        }

}

}

Output:

Exception in thread main java.lang.ArithmeticException:/by zero

Rest of the code….

 


Check more posts on exception handling here


Don't want to miss updates? Please click the below button!

Follow MindStick