Friday, October 16, 2015

Introduction to Exception Handling in Java

The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.
In this page, we will learn about java exception, its type and the difference between checked and unchecked exceptions.

What is exception

Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

What is exception handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario:
  1. statement 1;  
  2. statement 2;  
  3. statement 3;  
  4. statement 4;  
  5. statement 5;//exception occurs  
  6. statement 6;  
  7. statement 7;  
  8. statement 8;  
  9. statement 9;  
  10. statement 10;  
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the statement will be executed. That is why we use exception handling in java.


Do You Know ?
  • What is the difference between checked and unchecked exceptions ?
  • What happens behind the code int data=50/0; ?
  • Why use multiple catch block ?
  • Is there any possibility when finally block is not executed ?
  • What is exception propagation ?
  • What is the difference between throw and throws keyword ?
  • What are the 4 rules for using exception handling with method overriding ?

Hierarchy of Java Exception classes

hierarchy of exception handling

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions:
  1. Checked Exception
  2. Unchecked Exception
  3. Error

Difference between checked and unchecked exceptions

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) Scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.
  1. int a=50/0;//ArithmeticException  

2) Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.
  1. String s=null;  
  2. System.out.println(s.length());//NullPointerException  

3) Scenario where NumberFormatException occurs

The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.
  1. String s="abc";  
  2. int i=Integer.parseInt(s);//NumberFormatException  

4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
  1. int a[]=new int[5];  
  2. a[10]=50//ArrayIndexOutOfBoundsException  

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

Difference between throw and throws

1. A throw statement can be used to throw an Exception explicitly from the code where as a throws statement just declares that an Exception can be thrown. It doesn't actually throw and Exception

2.
--A throw statement is followed by an object of type Throwable e.g.

Exception e1=new Exception(); 
throw e1;

-- A throws statement is written in the definition of a constructor or a method e.g.

void m1() throws Exception{
    // any code here
}

3. A throw statement is an executable statement where as a throws statement is just a declarative statement

4. A throw statement is actually used at run time.. where as a throws statement is referred by the compiler at compile time. After compilation, throws has no effect at run time

5. A throw statement is used to throw both Checked and Unchecked Exceptions, while a throws statement should be used if an un-handled Checked exception is throws from a method or constructor.

Using Generic Collections

import java.util.*;

class GenericPractice{
    public static void main(String args[]){
        ArrayList<String> al=new ArrayList<String>();
        al.add(12);
        al.add("world");
        String s=(String)al.get(0);
        System.out.println(s);
        
    }
}

Creating Generic Type (class)

import java.util.*;

class Message<T>{
    private T msg;
    public void setMsg(T t){
        msg=t;
    }
    public T getMsg(){
        return msg;
    }
    public static void main(String[] args){
        
        Message<Object> m1=new Message<String>();
        m1.setMsg("Hello");
        String s1=m1.getMsg();
        System.out.println(s1);
        
        Message<Integer> m2=new Message<Integer>();
        m2.setMsg(12);
        int i=m2.getMsg();
        System.out.println(i);
    }
}

Examples of Generic Class, Interface, Method, Constructor


 1. Generics Class Example
public class Msg<T>
{
         public T t;
}
 
Msg<String> m1=new Msg<String>();
m1.t="Hello";

Msg<Integer> m2= new Msg<Integer>();
m2.t=5;


2. Generics Interface Example
public interface A1<T>
{
        public T m1();
}
 
public class B1 implements A1<String>{
        
        public String m1(){
 
        }
}
public class C1 implements A1<Rectangle>{
        public Rectangle m2(){
 
        }
}




3. Generic Constructor Example
class Sample {
  <T> Sample() {
              

               }
}

  Sample s1 = new <String> Sample();


4. Generic Method Example
static <T> void m1(T a, String s) {
    …
}

a1.m1(“hello”,”hi”);

File Management in Java (java.io.File)

Java File class represents the files and directory pathnames in an abstract manner. This class is used for creation of files and directories, file searching, file deletion etc.

The File object represents the actual file/directory on the disk. There are following constructors to create a File object:

Some important operations on File Object are listed here

1. Instantiating a java.io.File

Before you can do anything with the file system or File class, you must obtain a File instance. Here is how that is done: 
File file = new File("c:\\data\\input-file.txt");
Simple, right? The File class also has a few other constructors you can use to instantiate Fileinstances in different ways. 

2. Check if File Exists

Once you have instantiated a File object you can check if the corresponding file actually exists already. The File class constructor will not fail if the file does not already exists. You might want to create it now, right? 
To check if the file exists, call the exists() method. Here is a simple example: 
 
File file = new File("c:\\data\\input-file.txt");

boolean fileExists = file.exists();

3. File Length

To read the length of a file in bytes, call the length() method. Here is a simple example: 
File file = new File("c:\\data\\input-file.txt");

long length = file.length();

4. Rename or Move File

To rename (or move) a file, call the method renameTo() on the File class. Here is a simple example: 
File file = new File("c:\\data\\input-file.txt");

boolean success = file.renameTo(new File("c:\\data\\new-file.txt"));

5. Delete File

To delete a file call the delete() method. Here is a simple example: 
File file = new File("c:\\data\\input-file.txt");

boolean success = file.delete();
The delete() method returns boolean (true or false), indicating whether the deletion was successful. Deleting a file may fail for various reasons, like the file being open, wrong file permissions etc. 

6. Check if Path is File or Directory

File object can point to both a file or a directory. 
You can check if a File object points to a file or directory, by calling its isDirectory() method. This method returns true if the File points to a directory, and false if the File points to a file. Here is a simple example: 
File file = new File("c:\\data");

boolean isDirectory = file.isDirectory();

7. Read List of Files in Directory

You can obtain a list of all the files in a directory by calling either the list() method or thelistFiles() method. The list() method returns an array of String's with the file and / or directory names of directory the File object points to. The listFiles() returns an array of File objects representing the files and / or directories in the directory the File points to. 
Here is a simple example: 
File file = new File("c:\\data");

String[] fileNames = file.list();

File[]   files = file.listFiles();

 

 All Methods of File class 

(Do not mug up all the method names. Just try to remember those which are used in programs)

1public String getName()
Returns the name of the file or directory denoted by this abstract pathname.
2public String getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
3public File getParentFile()
Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.
4public String getPath()
Converts this abstract pathname into a pathname string.
5public boolean isAbsolute()
Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is absolute, false otherwise
6public String getAbsolutePath()
Returns the absolute pathname string of this abstract pathname.
7public boolean canRead()
Tests whether the application can read the file denoted by this abstract pathname. Returns true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise.
8public boolean canWrite()
Tests whether the application can modify to the file denoted by this abstract pathname. Returns true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
9public boolean exists()
Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise
10public boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise.
11public boolean isFile()
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file. Returns true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise
12public long lastModified()
Returns the time that the file denoted by this abstract pathname was last modified. Returns a long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs.
13public long length()
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.
14public boolean createNewFile() throws IOException
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. Returns true if the named file does not exist and was successfully created; false if the named file already exists.
15public boolean delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Returns true if and only if the file or directory is successfully deleted; false otherwise.
16public void deleteOnExit()
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
17public String[] list()
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
18public String[] list(FilenameFilter filter)
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
20public File[] listFiles()
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
21public File[] listFiles(FileFilter filter)
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
22public boolean mkdir()
Creates the directory named by this abstract pathname. Returns true if and only if the directory was created; false otherwise
23public boolean mkdirs()
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Returns true if and only if the directory was created, along with all necessary parent directories; false otherwise.
24public boolean renameTo(File dest)
Renames the file denoted by this abstract pathname. Returns true if and only if the renaming succeeded; false otherwise
25public boolean setLastModified(long time)
Sets the last-modified time of the file or directory named by this abstract pathname. Returns true if and only if the operation succeeded; false otherwise .
26public boolean setReadOnly()
Marks the file or directory named by this abstract pathname so that only read operations are allowed. Returns true if and only if the operation succeeded; false otherwise.

Program to display all files in given folder with permissions and size

import java.io.*;

class FileUtility{
    public static void main(String[] args){
        File f1=new File(args[0]);
        if(!f1.exists()){
            System.out.println("File does not exists");
            return;
        }
        if(f1.isFile()){
            System.out.println("Folder required");
            return;
        }
        File[] arr=f1.listFiles();
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i].getName()+"\t");
            if(arr[i].canRead()){
                System.out.print("R");
            }           
            if(arr[i].canWrite()){
                System.out.print("W");
            }           
            if(arr[i].canExecute()){
                System.out.print("X");
            }           
            System.out.print("\t");
            System.out.print(arr[i].length()+" Bytes\t");
            if(arr[i].isFile()){
                System.out.print("File");
            }
            else{
                System.out.print("Folder");
            }
           
            System.out.println();
        }
    }
}