Friday, 31 May 2013

4. Exceptions in JAVA

throw Keyword: We can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.

Differences between throws and throw:
  • throw is used to explicitly throw an exception where as throws is used to declare an exception.
  • throw is followed by an instance where as throws is followed by class.
  • throw is used with in method(we can use throw keyword in static block also) and throws is used with the method signature.
  • we can not throw multiple exceptions and we can declare multiple exceptions using throws.
  • throw transfers control to caller, while throws is suggest for information and compiler checking.
  • throw keyword is used to throw Exception from any method or static block in Java while throws keyword, used in method declaration, denoted which Exception can possible be thrown by this method.
  • throw keyword can also be used to break a switch statement without using break keyword as shown in below example:
  •            switch(number){
                   case 1:
                         throw new Exception1("Exception number 1");
                  case 2:
                       throw new Exception2("Exception number 2");
               }
  • throws keyword gives a method flexibility of throwing an Exception rather than handling it. with throws keyword in method signature a method suggesting its caller to prepare for Exception declared in throws clause, specially in case of checked Exception and provide sufficient handling of them. On the other hand throw keyword transfer control of execution to caller by throwing an instance of Exception. throw keyword can also be used in place of return as shown in below example:
           private static boolean startSystem() {
             throw new UnsupportedOperationException("Not yet implemented");
            }

As in above method startSystem() should return boolean but having throw in place compiler understand that this method will always throw exception.

Summary Of Exception handling in JAVA:
  • Normal program execution is immediately branched when an exception is thrown. 
  • Checked exceptions must be caught or forwarded. This can be done in a try ... catch statement or by defining the exception in the method definition. 
  • The exception is caught by the first catch block whose associated exception class matches the class or a superclass of the thrown exception. 
  • If no matching catch block is found in the exception chain, the thread containing the thrown exception is terminated.
  • The finally block after a try ... catch statement is executed regardless whether an exception is caught or not.
  • Returning within a finally block breaks the exception chain to the invoker even for uncaught exceptions.

No comments:

Post a Comment