Exception Handling in java

Exception Handling in Java is one of the important functions to handle runtime errors so that the normal flow of the application can not be affected or stop.

In this tutorial, we will learn about Java exceptions, their types, and the difference between checked and unchecked exceptions in java.

What is Exception Handling in java?

Exception handling is not a new term, it is available for every programming language. What is an exception?- Exception is an abnormal condition according to Dictionary.

In Java, an exception is an event that interrupts the normal flow of the program. It is an object which comes at runtime and exception handling in java is a mechanism to manage the runtime errors like ClassNotFoundException, IO, SQLException, RemoteException, etc.

Error Vs Exception

ErrorException
Impossible to recover from the errors.Possible to recover from the exception.
Errors are the unchecked type.It can be unchecked or checked.
It occurs at run time.It can happen during compilation or run time.
Caused by the environment in which the program is runningCaused by the application.

Types of Exception handling in java:

exception handling in java

There are mainly two types of exceptions i.e. checked and unchecked. An error exception is considered as the unchecked exception. But, according to Oracle, there are three types of exceptions.

What are the differences between Checked, unchecked exceptions?

Checked exception Unchecked exceptions
Checked exceptions occur at compile time.Unchecked exceptions occur at runtime.
The compiler checks a checked exception.The compiler does not check these types of exceptions.
These types of exceptions can be handled at the time of compilation.These types of exceptions cannot be a catch or handle at the time of compilation, because they get generated by the mistakes in the program.
They are the sub-class of the exception class.They are runtime exceptions and hence are not a part of the Exception class.
Here, the JVM needs the exception to catch and handle.Here, the JVM does not require the exception to catch and handle.
Examples of Checked exceptions: File Not Found ExceptionNo Such Field ExceptionInterrupted ExceptionNo Such Method ExceptionClass Not Found ExceptionExamples of Unchecked Exceptions: No Such Element ExceptionUndeclared Throwable ExceptionEmpty Stack ExceptionArithmetic ExceptionNull Pointer ExceptionArray Index Out of Bounds ExceptionSecurity Exception

Error Exceptions: Errors represent serious and usually irretrievable conditions like a library variance, infinite recursion, or memory losses. And even though they don’t extend RuntimeException, they are also unchecked.

Basic Example Of Exception Handling in java:

Class Exception{

        public static void main(String args[]){
          try {

              // code that will be executed and raise an exception

              }


          catch(Exception e){
                     // rest of the program
                    }

 }

}

In this example, Inside the main method, we have a try block in this try block the code will be written. That means the try block contains the code which raised the exception and then the raised exception is handled in the catch block. let’s see in a small program.

// This Java program to shows how exception is thrown.
class ThrowsExecption{
	
	public static void main(String args[]){
		
		String str = null;
		System.out.println(str.length());
		
	}
}

Output:

Exception in thread "main" java.lang.NullPointerException
    at ThrowsExecp.main(File.java:8)

How to use try-catch clause

try {
// block of code to monitor for errors
// the code you think can raise an exception
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// optional
finally {
//this block of code to be executed after try block codes
}

Some Scenarios of Java Exceptions

  1. NullPointer Exception in Java
class NullPointerDemo
{
    public static void main(String args[])
    {
        try {
            String x = null; //null value
            System.out.println(x.charAt(0));
        } catch(NullPointerException e) {
            System.out.println("NullPointerException:");
        }
    }
}


OutPut:

NullPointerException..

2. Arithmetic exception in java

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


Output:


Can not divide a number by 0

3. FileNotFound Exception

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
 class FilenotFoundDemo {
 
    public static void main(String args[])  {
        try {
 
            // Following file does not exist
            File file = new File("D://file.txt");
 
            FileReader fr = new FileReader(file);
        } catch (FileNotFoundException e) {
           System.out.println("File doesn't exists");
        }
    }
}

OutPut:


File doesn't exists

4. RuntimeException: Any exception which occurs during runtime is called a RuntimeException.

There are many exceptions that are present in java.

What are the Causes Of OutOfMemoryError?

If an application has too many finalizers, then the class objects having the Finalize method are not reclaimed by the garbage collector immediately but are queued up for finalization at a later time. Sometimes, the finalization can’t keep up with time, and heap memory is filled up resulting in OutOfMemoryError.

Another reason for OutOfMemoryError is that the heap size specified may be insufficient for the application.

Leave a Reply

Your email address will not be published.