What is an Exception?

An Exception in Java is an unexpected event that occurs during program execution, It can cause the program to terminate abnormally by affecting the flow of program instructions.

An exception in java may occur due to many reasons.

Some possibilities for raising an Exception:

1) Entering of invalid data by the user

2) Loss of network connection

3) Device failure

4) Errors in code

5) Opening an unavailable file

Java is strong enough to hold such Exceptions. By using the java exception handling mechanism, we can provide a meaningful message to the user about the issue rather than a system generated message, that may not be understandable to a user.

Why an Exception Occurs?

There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc.

 Exception Hierarchy

exceptions hierarchy programming9

 

From the above image, all the Exception classes are the sub types of java.lang.Exception class.

Throwable class contains two classes.

1.Error

2.Exception

Error Class

Errors are the problems that arise beyond the control of the user or the programmer. Errors are not exceptions and they can be ignored.

For example, if stack overflow occurs, an error will arise. They can be ignored at the time of compilation. We can not handle these errors Exceptions

Exception Class

An exception occur within a method, it creates an object. This object is called the Exception object.

Exceptions can be caught and can be handled. There are 2 types of Exceptions.

Runtime Exceptions

Compile Time Exceptions or Checked Exceptions

Runtime Exceptions

Runtime Exceptions are also called as Unchecked Exceptions. They occur due to a programming error. These are checked only at runtime but not at compile time.

These include programming bugs, such as logical errors or improper use of an API.

Runtime Exceptions can be ignored by the programmer.

Note:"Runtime Exceptions occur because of the user fault".

 

Some of the Runtime Exceptions are

1. IllegalArgumentException - Improper use of an API

EXAMPLE:

public void IllegalException(String title) {
    this.title = title;
}
IllegalException(123)

 

If we attempt to call this method while passing a non-String value (such as an int), as seen above, the compiler will catch the issue and prevent us from even executing the application. In this case, the compiler issues an error indicating that int cannot be converted to a String: Hence, it shows IllegalArgumentException.

 

2. NullPointerException - Null pointer access

EXAMPLE:

public class Main {
   public static void main(String[] args) {
      Object ref = null;
      ref.toString(); // this will throw a NullPointerException
   }
}

Output

Exception in thread "main" java.lang.NullPointerException
	at Main.main(Main.java:4)
In the above example, the application try to use an object reference which has a null value.

3.ArrayIndexOutOfBoundsException - Out-of-bounds array access EXAMPLE:

class Main
{
public static void main(String args[])
{
int n[]={2,4,6,8};
System.out.println(n[5]);
}
}

OUTPUT:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Main.main(Main.java:6)

In the above example, we declared an array of size 4 and trying to call the 5th element. Hence, it shows ArrayIndexOutOfBoundsException.

4.ArithmeticException - Dividing a number by 0

 

public class ArithmeticException {
 
    public static void main(String[] args) {
        int a=0, b=4 ;
        int c = b/a;
        System.out.println("Value of c : "+c);
    }
 
}

 

OUTPUT:

Exception in thread "main" java.lang.ArithmeticException: 

             at  java.ArithmeticException.main(ArithmeticException.java:5)

In the above example, the number is divided by '0'. Hence, it shows ArithmeticException.

 

Checked Exceptions

Checked Exceptions are checked at compile time but not at runtime.

Examples for checked exceptions are, IO Exception, SQLException, ClassNotFoundException, etc.

FileNotFoundException

import java.io.File;
import java.io.FileReader;

public class Checked
{

  public static void main (String args[])
  {
    File file = new File ("E://file.txt");
    FileReader fr = new FileReader (file);
  }
}

 

FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(file);

In the above example, we used the FileReader class to read a data from a file, but the file specified in its constructor doesn't exist. Hence, it shows FileNotFoundException.