Wednesday, 7 September 2016

when to use try catch over throws key word in java

hello all
you should be careful while using throws keyword in method declaration. if you do so then the exception that may thrown from your method may go unnoticed. so it is good to use try catch for a piece of code and handle the exception.

class Example
{
   public void method()throws Exception
      {
   //the exception may come here , but we cant notice as we have declared method as throws        //exception.
     //so use try catch here.
      }
}

//or you can have another choice, use try catch where you call method

Example e = new Example();
try{
e.method
}
catch(Exception e)
{
 //handle here
}

No comments:

Post a Comment