Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaJava Program to Handle Unchecked Exception

Java Program to Handle Unchecked Exception

Exceptions are the issues arising at the runtime resulting in an abrupt flow of working of the program. Remember exceptions are never thrown at the compile-time rather always at runtime be it of any type. No exception is thrown at compile time. Throwable Is super-class of all exceptions and errors too. Now there is an urgency to deal with them for which a concept is defined in Java language known as ‘Exception Handling Techniques’

There are two types of exceptions defined as follows 

  • Checked Exceptions
  • Unchecked Exceptions

Real-world Illustration: Exceptions

Consider an employee leaving home for office. He is being monitored by the parent to take ID card stuff and all things as they can think of. Though the employee knows out everything but still being monitored. Now employee leaves out the home still somehow was delayed as his vehicle tyre gets punctured because of which result is that he arrived late to office. Now these wanted things that disrupt his daily routine is referred as Exceptions in Java. Parent actions that helped him though he checked those stuffs but if someday somehow missed and the employee gets things correctly at home itself is referred as ‘checked exception’ in Java. The actions over which parental access does not have any control is referred as ‘unchecked exceptions.’ Here, parent or monitoring authority is referred as ‘Compilers’ in programming languages. Exceptions that can be detected by compilers are checked exceptions and those who can not be detected are called unchecked exceptions.

Approach: Now, in order to deal with exceptions, the concept proposed out are exception handling techniques. Straight away diving onto the concept for unchecked exceptions.

Unchecked Exception

These types of Exceptions occur during the runtime of the program.  These are the exceptions that are not checked at a compiled time by the compiler. In Java exceptions under Error and Runtime Exception classes are unchecked exceptions, This Exception occurs due to bad programming.

  1. Errors class Exceptions like  StackOverflow, OutOfMemoryError exception, etc are difficult to handle
  2. Runtime Exceptions like IndexoutOfBoundException, Nullpointer Exception, etc can be handled with the help of try-Catch Block

There are 2 major Unchecked Exceptions which are faced generally by programmers namely IndexOutOfBoundsExcepetion and NullPointerException. They are discussed below with the help of an example also, we will implement them and discuss how to handle them out. Both the major approaches are proposed as below:

  1. IndexOutOfBoundsException
  2. NullPointerException

Case 1: (Array)IndexoutOfBoundException: This Exception occurs due to accessing the index greater than and equal to the size of the array length. The program will automatically be terminated after this exception. In simpler terms, a memory is being tried to accessed which the current data structure is not holding by itself. Here this exception is defined over data structure namely ‘Arrays‘.

Java




// Importing Classes/Files
import java.io.*;
 
class GFG {
 
    // Main Driver Function
    public static void main(String[] args)
    {
        // Array containing 4 elements
        int a[] = { 1, 2, 3, 4 };
 
        // Try to access elements greater than
        // index size of the array
        System.out.println(a[5]);
    }
}


Output:

Handling ArrayIndexoutOfBoundException: Try-catch Block we can handle this exception try statement allows you to define a block of code to be tested for errors and catch block captures the given exception object and perform required operations. The program will not terminate.

Java




// Importing Classes/Files
import java.io.*;
 
public class GFG {
 
    // Main Driver Method
    public static void main(String[] args)
    {
        // Inserting elements into Array
        int a[] = { 1, 2, 3, 4, 5 };
 
        // Try block for exceptions
        try {
 
            // Forcefully trying to access and print
            // element/s beyond indexes of the array
 
            System.out.println(a[5]);
        }
 
        // Catch block for catching exceptions
        catch (ArrayIndexOutOfBoundsException e) {
 
            // Printing display message when index not
            // present in a array is accessed
            System.out.println(
                "Out of index  please check your code");
        }
    }
}


Output:

Case 2: NullPointerException: This exception occurs when trying to access the object reference that has a null value.

Java




// Importing Classes/Files
import java.io.*;
 
public class GFG {
    // Main Driver Method
    public static void main(String[] args)
    {
 
        // Instance of string a has null value
        String a = null;
 
        // Comparing null value with the string value
        // throw exception and Print
        System.out.println(a.equals("GFG"));
    }
}


Output:

Handling Technique for NullPointerException

Java




// Importing Files/Classes
import java.io.*;
 
public class GFG {
 
    // Driver Main Method
    public static void main(String[] args)
    {
        // Assigning NULL to string
        String m = null;
 
        // Try-Catch Block
        try {
           
            // Checking the null value with GFG string
            // and throw exception
            if (m.equals("GFG")) {
                // Print String
                System.out.println("YES");
            }
        }
 
        // Try-Catch Block
        catch (NullPointerException e) {
 
            // Handles the exception
            System.out.println(
                "Object reference cannot be null");
        }
    }
}


Output:

RELATED ARTICLES

Most Popular

Recent Comments