Sunday, April 12, 2020

Exception Handling In Java-Part 1



Exceptions are unplanned or unwanted situations ,which gets occurred during execution of programming in run time or compile time and disturbs the flow of execution.

Based on class libraries, Java has various types of exceptions i.e built-in exceptions. Even user defined exceptions are present in java.

Built-in exceptions are due to libraries so they are suitable to explain certain error situations.
Types of Built-in exception-



1.     Arithmetic Exception –
Arithmetic means numbers,so these are occurred due to numbers .It is unchecked error and then exception occurs like –when divide by 0 causes mathematical problem at run time as it cannot handle this situation.During that time arithmetic exception is thrown.

Code-

class ArithmeticException_Demo
{
    public static void main(String args[])
    {
        try {
            int a = 30, b = 0;
            int c = a/b;  // cannot divide by zero
            System.out.println ("Result = " + c);
        }
        catch(ArithmeticException e) {
            System.out.println ("Can't divide a number by 0");
        }
    }
}

Output-

Can’t divide a number by 0


2.     ArrayIndexOutOfBoundsException –
Whenever array elements are entered above specified length it gives exception which is called the ‘ArrayIndexOutOfBoundsException'.
ArrayIndexOutOfBoundsException implements a ‘serializable’ interface i.e serial by serial entry and derives from the ‘indexOutOfBoundsException’ which in turn is derived from the RuntimeException class which is a subclass of the ‘exception’ class. It is unchecked exception and does not need to be called from method explicitly.
Code-
Example 1-
class Main { 
    public static void main(String[] args) { 
        //array of subjects. There are 5 elements.
        String[] subjects = {"Maths","Science","French","Sanskrit", "English"};  

        //for loop iterates from 0 to 5
        for(int i=0;i<=subjects.length;i++) {      
                        System.out.print(subjects[i] + " ");     
        } 
    }
Output-
Maths Science French Sanskrit English Exception in thread “main”java.lang.ArrayIndexOutOfBoundsException : 5
    At Main.main(Main.java:9)
Simply this exception indicates array has accessed been accessed with illegal index i.e index isgreater than or equal to size of array or negative.
Example 2-
class ArrayIndexOutOfBound_Demo
{
    public static void main(String args[])
    {
        try{
            int a[] = new int[5];
            a[6] = 9;
        }
        catch(ArrayIndexOutOfBoundsException e){
            System.out.println ("Array Index is Out Of Bounds");
        }
    }
}

Output-
Array Index is out of Bounds.
3.    ClassNotFoundException
As name given,class not found means class definition npt available or found then this exception occurs.
java.lang.classNotFoundException in Java is a subclass of Exception and occurs when Java Virtual Machine tries to load  class and doesn't found it.

 4.     FileNotFoundException-

According to name file not found this exception occurs when file is not present or cannot be accesed. If in code it is written to get path of file and file on same path is not present then this exception occurs.

private JarFile getJarFile(URL url) throws IOException {
    // Optimize case where url refers to a local jar file
    if (isOptimizable(url)) {
        //HACK
        //FileURLMapper p = new FileURLMapper (url);
        File p = new File(url.getPath());
 
        if (!p.exists()) {
            throw new FileNotFoundException(p.getPath());
        }
        return new JarFile (p.getPath());
    }
    URLConnection uc = getBaseURL().openConnection();
    uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
    return ((JarURLConnection)uc).getJarFile();
}

5.     IOException-

IOExceptions are thrown when there is any input / output file operation issues while application perform certain tasks accessing the files. IOException is a checked exception and application developer has to handle in correct and proper manner. IOException has many subcases like filenotfoundexception as this occurs when file is not present and similarly it gives input missing which cause IOException.

Code-

static ArrayList<BufferedImage> getFrames(File gif) throws IOException {
    ArrayList<BufferedImage> frames = new ArrayList<BufferedImage>();
    ImageReader ir = new GIFImageReader(new GIFImageReaderSpi());
    ir.setInput(ImageIO.createImageInputStream(gif));
    for (int i = 0; i < ir.getNumImages(true); i++) {
        frames.add(ir.read(i));
    }
    // Release resources for Garbage Collection
    ir.dispose();
    return frames;
} 



6.     InterruptedException-

    Thrown when a thread is waiting, sleeping,or otherwise occupied, and the thread is                              interrupted,either before or during the activity. Usually used to test whether the current thread has        been interrupted, and if so, to immediately throw this exception.

      if (Thread.interrupted())  // Clears interrupted status!
       throw new InterruptedException();



Diksha Avhad
K-3


12 comments: