Showing posts with label Exception. Show all posts
Showing posts with label Exception. Show all posts

Checked Exceptions Vs Unchecked Exceptions in Java

A checked exception is any subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.

Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked.
 
With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method.
 
Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be, as they tend to be unrecoverable.

ArrayIndexOutOfBoundsException


    java.lang
Class ArrayIndexOutOfBoundsException
java.lang.Object
   java.lang.Throwable
       java.lang.Exception
           java.lang.RuntimeException
               java.lang.IndexOutOfBoundsException
                   java.lang.ArrayIndexOutOfBoundsException

An ArrayIndexOutOfBoundsException is thrown when an out-of-range index is detected by an array object. An out-of-range index occurs when the index is less than zero or greater than or equal to the size of the array.

    Synopsis
 
Class Name:
 
    java.lang.ArrayIndexOutOfBoundsException
 
Superclass:
 
    java.lang.IndexOutOfBoundsException

 Constructor Detail
           ArrayIndexOutOfBoundsException 
public ArrayIndexOutOfBoundsException()
 
Constructs an ArrayIndexOutOfBoundsException with no detail message.

          ArrayIndexOutOfBoundsException
 
public ArrayIndexOutOfBoundsException(int index)
 
Constructs a new ArrayIndexOutOfBoundsException class with an argument indicating the illegal index.
 
Parameters:
         index - the illegal index.

          ArrayIndexOutOfBoundsException
 
public ArrayIndexOutOfBoundsException(String s)
 
Constructs an ArrayIndexOutOfBoundsException class with the specified detail message.
 
Parameters:
         s - the detail message.
 
Example
 
In this example we are going to see how we can catch the exceptionArrayIndexOutOfBoundException. ArrayIndexOutOfBoundException is thrown when we have to indicate that an array has been accessed with an illegal index. 
 
Suppose we have declared an array of int and the size of the array is 6, that means  that this array can store six values. Now suppose if want to access the seventh variable which does not exist, then it will throws the exception ArrayIndexOutOfBound. It means that there is no other value instead after that we are forcing the array to give the next value. 
The code of the program is given below:
try{
        int a[] =new int[6];
                for(int i = 0; i<7; i++){
               
                 a[i]=i;
                }      
        }catch(Exception e){
               System.out.println("Exception:"+e);
                }

output:
Exception:java.lang.ArrayIndexOutOfBoundException:6

Create and How to use your own Exceptions

Creating Your Own Exception Class

● Steps to follow
 
– Create a class that extends the RuntimeException or the
 
Exception class
 
– Customize the class
 
● Members and constructors may be added to the class
 
● Example:
 
 class HateStringExp extends RuntimeException {
 
 /* some code */
 
 }

How To Use Your Own Exceptions
 
class TestHateString {
 
 public static void main(String args[]) {
 
 String input = "invalid input";
 
 try {
 
 if (input.equals("invalid input")) {
 
 throw new HateStringExp();
 
 }
 
System.out.println("Accept string.");
 
 } catch (HateStringExp e) {
 
 System.out.println("Hate string!”);
 
}
 
 } }

What is difference between throw and throws in Java?


One declares it, and the other one does it

Throw is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable. 


public void myMethod(int param) throws MyException
{
      if (param < 10)
     {
            throw new MyException("Too low!);
     }
    //Blah, Blah, Blah...
}


The Throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method. 


If a method is throwing an exception, it should either be surrounded by a try catch block to catch it or that method should have the throws clause in its signature. Without the throws clause in the signature the Java compiler does not know what to do with the exception. The throws clause tells the compiler that this particular exception would be handled by the calling method.

Throwing Exception


The throw Keyword
A program can explicitly throw an exception using the throw statement besides the implicit exception thrown
The general format of the throw statement is as follows:

throw ThrowableInstance
 
ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
 
2 ways to obtain Throwable object:
Using a parameter into a catch clause


Creating one with a new operator.
 

try {
 

throw new NullPointerException("created");
 

}catch (NullPointerException e) {
 

throw e; //rethrow the Exception
 

}
 
The throws Keyword
throws " is a keyword defined in the Java programming language. Keywords are basically reserved words which have specific meaning relevant to a compiler in Java programming language likewise the throw keyword indicates the following :
--- The throws keyword in Java programming language is applicable to a method to indicate that the method raises particular type of exception while being processed.
--- The throws keyword in Java programming language takes arguments as a  list of the objects of type java.lang.Throwable class.
--- when we use the throws with a method it is known as ducking. The  method calling a method with a throws clause is needed to be enclosed within the try catch blocks.
 
This is the general form of a method declaration that includes a throws clause:
 
         type method-name(parameter-list) throws exception-list

       {
       // body of method
       }

Handling the Unreachable Code Problem - Exception


The multiple catch blocks can generate unreachable code error i.e. if the first catch block contains the Exception class object then the subsequent catch blocks are never executed.  This is known as Unreachable code problem.
Example:
try{
System.out.println(3/0);         //here arithmetic exception has come


System.out.println(“Pls. print me.”);
 

}catch( Exception e){
 

 System.out.println(“Exception 1.”);
 

}
 

catch(ArithmeticException e1){    //here unreachable code problem has come. Compilation error
System.out.println(“Exception e2”);
 

}
 

 }
 

 }

To avoid this, the last catch block in multiple catch blocks must contain the generic class object that is called the Exception class. This exception class being the super class of all the exception classes and is capable of  catching any  types of exception. The generic Exception class can also be used with multiple catch blocks.
 

Example:
 

try{
System.out.println(3/0);    //here arithmetic exception has come
 

System.out.println(“Pls. print me.”);
 

}catch( ArithmeticException e){
 

 System.out.println(“Exception 1.”);
 

}
 

catch(Exception e1){     //OK
 

System.out.println(“Exception e2”);
 

}
 

 }
 

 }

The Finally block- Exception


The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

Syntax:
 

try {
 

<code to be monitored for exceptions>
 

} catch (<ExceptionType1> <ObjName>) {
 

<handler if ExceptionType1 occurs>
 

} ...
 

} finally {
 

<code to be executed before the try block ends>
 

}

Multiple Catch- Exception


So far we have seen how to use a single catch block, now we will see how to use more than one catch blocks in a single try block.In Java when we handle the exceptions then we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that may be generated while running the program i.e. you can use more than one catch clause in a single try block however every catch block can handle only one type of exception. this mechanism is necessary when the try block has statement that raise  different type of exceptions.
The syntax for using this clause is given below:-
 

try{
 

}
 

catch(Exception e1){
 

}
 

catch(Exception e2){
 

}
 

when an exception occurs normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. If first one catch block has not matched then the second one is matched and so on....
 

example:
 

class DivByZero {
public static void main(String args[]) {
 

try{
System.out.println(3/0);    //here arithmetic exception has come
  

System.out.println(“Pls. print me.”);

}catch( ArrayIndexOutOfBoundsException e){
 

 System.out.println(“Exception 1.”); 

}
 

catch(ArithmeticException e1){
 

System.out.println(“Exception e2”);
 

}
 

 }
 

 }
 

explanation:
 

In this example we have used two catch clause catching the exception ArrayIndexOutOfBoundsException and  Arithmetic Exception in which the statements that may raise exception are kept under the try block. When the program is executed, an exception will be raised. Now that time  the first catch block is skipped and the second catch block handles the error.

Nested try Statements- Exception


Nested try Statements
 

Class NestTry {
 

public static void main (String args[]) {
 

try {
 

//….
 

//….
 

try {
 

//…
 

//….
 

}catch (ExceptionType exOb) {
 

//….
 

}
 

}catch (ExceptionType exOb) {
 

//….
 

}
 

}
 

}
 

Each time a try block is entered, the context of that exception is pushed n the stack.
If an inner try statement does not have a catch handler for a particular exception, the stack is unwounded and next try statement’s catch handlers are inspected for a match.
Continues till 1 catch statement succeeds, or until all try statements are exhausted.
If no catch statement matches, then the Java run-time will handle the exception.

Catching Exception:try/catch block

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. In the block preceded by catch, we put the code that will be executed if and only if an exception of the given type is thrown. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try

{
   //Protected code
}catch(ExceptionName e1)
{
   //Catch block
}
 A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

Example:

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.

import java.io.*;

public class ExcepTest{

public static void main(String args[]){
      
     try{
        
        int a[] = new int[2];
         
        System.out.println("Access element three :" + a[3]);
      
     }catch(ArrayIndexOutOfBoundsException e){
        
        System.out.println("Exception thrown  :" + e);
      
     }
    
        System.out.println("Out of the block");

    }

}

This would produce following result:

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Exception Hierarchy

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors.


What happens when an exception occurs?

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).


                                                     The call stack 
The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.
The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.



                                          Searching the call stack for the exception handler.

What is Exception?

Exceptions in Java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, unable to get connection exception and so on.
An exception can occur for many different reasons, including the following:
  • A user has entered invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications, or the JVM has run out of memory.
Exception Example
 class DivByZero {
 public static void main(String args[]) {
 System.out.println(3/0);
 System.out.println(“Pls. print me.”);
 }
 }
Example: Default Exception
Handling

● Displays this error message
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at DivByZero.main(DivByZero.java:3)

● Default exception handler
– Provided by Java runtime
– Prints out exception description
– Prints the stack trace
 
● Hierarchy of methods where the exception occurred
– Causes the program to terminate
Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three categories of exceptions:
  • Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. 
  • Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.
  • Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More