Exceptions

  • An exceptions is a problem that occurs during program execution.
  • Exceptions cause abnormal termination of the Program.
  • Exception handling is a powerful mechanism that handles runtime errors to maintain normal application flow.
  • An exception can occur for many different reasons. Some examples
  • A user has entered invalid data.
  • A file that need to be opened cannot be found.
  • A network connection has been lost in the middle of communications.
  • Insufficient memory & other issues related to physical resources.
  • Exception Handling –
  • Exception can be caught using a combination of try & catch keyword.
  • A try/catch block is placed around the code that might generates an exception.
  • Syntax-
    try{
         .....
      }catch(Exception e){
        ......
     }
  • A catch statement involves declaring the type of exception you are trying to catch.
  • If an exception Occurs in the try block , the catch block that follows the try is checked .
  • If the type of exception that Occurred is listed in catch block, the exception is passed into a method parameter.
  • The Exception type can be used to catch all possible exception.
  • Example-
    public class Mycalss{
          public static void main(String args[]){
               try{
                    int a[] = new int[2];
                    System.out.println(a[5]);  
                }catch(Exception e){
                    System.out.println("An error Occurred");
                }
       }
    }
    Output-
    An error Occurred.
  • Without try/catch block this code should crash the program . a[5] does not exist.

More On Exceptions