The Wayback Machine - https://web.archive.org/web/20241123075309/https://www.geeksforgeeks.org/java-program-to-handle-unchecked-exception/
Open In App

Java Program to Handle Unchecked Exception

Last Updated : 27 Apr, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:



Previous Article
Next Article

Similar Reads

Java Program to Handle Checked Exception
Checked exceptions are the subclass of the Exception class. These types of exceptions need to be handled during the compile time of the program. These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error. ClassNotFoundException, IOException, SQLException etc are the examples
5 min read
Java Program to use Catch to Handle the Exception
The exception is the event occurs when the program is executing. Due to this exception, the normal flow of the program will get disrupts. Whenever an exception occurs in the method, the method creates an object and sends that object to the runtime system. For example, the file needs to be open is not found, class not found exception, Arithmetic Exc
3 min read
Java Program to Handle the Exception Methods
An unlikely event which disrupts the normal flow of the program is known as an Exception. Java Exception Handling is an object-oriented way to handle exceptions. When an error occurs during the execution of the program, an exception object is created which contains the information about the hierarchy of the Exception and other information which is
4 min read
Java Program to Handle the Exception Hierarchies
Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program and terminates the program. Exception Handling: The process of dealing with exceptions is known as Exception Handling. Hierarchy of Exceptions: Object class is the parent class of all the classe
4 min read
How to Handle the SSL(HTTPs) Certification Path Exception in Android Applications?
If you haven't been stung by the below-mentioned exception when running a Java program created by you on your system that connects to an SSL server (HTTPS), be prepared for a bad experience at some time in your development career. Exception: PKIX path construction failed: sun.security.provider.certpath.SunCertPathBuilder Exception: No valid certifi
4 min read
Checked vs Unchecked Exceptions in Java
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. In Java, there are two types of exceptions: Checked exceptionsUnchecked exceptions Understanding the difference between checked and unchecked exceptions is crucial for
5 min read
Java Program to check the validity of a Password using User Defined Exception
Password checker program basically checks if the password is valid or not based on password policies mention below: Password should not contain any space. Password should contain at least one digit(0-9). Password length should be between 8 to 15 characters. Password should contain at least one lowercase letter(a-z). Password should contain at least
4 min read
Output of Java program | Set 12(Exception Handling)
Prerequisites : Exception handling , control flow in try-catch-finally 1) What is the output of the following program? public class Test { public static void main(String[] args) { try { System.out.printf("1"); int sum = 9 / 0; System.out.printf("2"); } catch(ArithmeticException e) { System.out.printf("3"); } catch(Exce
3 min read
Java Program to Handle Runtime Exceptions
RuntimeException is the superclass of all classes that exceptions are thrown during the normal operation of the Java VM (Virtual Machine). The RuntimeException and its subclasses are unchecked exceptions. The most common exceptions are NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, InvalidArgumentException etc. The NullPo
2 min read
Java Program to Handle Divide By Zero and Multiple Exceptions
Exceptions These are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program. Handling Multiple exceptions: There are two methods to handle multiple exceptions in java. Using a Single try-catch block try statement allows you to define a block of code to be tested f
3 min read
Java Program to Handle Duplicate Elements in a PriorityQueue While Maintaining Order
In Java, elements in a Priority Queue are arranged according to their priority, which is based on a priority heap. When there are duplicate items, the default comparison method is to use a comparator that is given or to compare the elements according to their natural ordering. We can use a custom comparator or wrapper class to handle duplicates and
3 min read
How to Handle java.lang.UnsatisfiedLinkError in Java?
Java.lang.UnsatisfiedLinkError is a subclass of LinkageError Class. When Java Virtual Machine(JVM) did not find the method Which is declared as "native" it will throw the UnsatisfiedLinkError. Now let us do discuss when and why does it occur. Java.lang.UnsatisfiedLinkError occurs during the compilation of the program. It is because of the reason th
3 min read
How to Handle a java.lang.NegativeArraySizeException in Java?
In Java, NegativeArraySizeException is the pre-defined class that can be used to represent the unchecked exception. It is a subclass of the java.lang package, and it can be used to identify that an array was attempted to be created with a negative size, which is not allowed in Java. In this article, we will learn how to handle a java.lang.NegativeA
2 min read
How to handle a java.lang.IndexOutOfBoundsException in Java?
In Java programming, IndexOutOfBoundsException is a runtime exception. It may occur when trying to access an index that is out of the bounds of an array. IndexOutOfBoundsException is defined as the RuntimeException. It can be used to find the out-of-bound run-time errors of an array. It is a part of the java.lang package. In this article, we will l
2 min read
How to Handle a java.lang.ArithmeticException in Java?
In Java programming, the java.lang.ArithmeticException is an unchecked exception of arithmetic operations. This means you try to divisible by zero, which raises the runtime error. This error can be handled with the ArthmeticException. ArithmeticException can be defined as a runtime exception that can occur during an arithmetic operation due to the
2 min read
Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o
4 min read
Java | Exception Handling | Question 1
Predict the output of following Java program class Main { public static void main(String args[]) { try { throw 10; } catch(int e) { System.out.println("Got the Exception " + e); } } } (A) Got the Exception 10 (B) Got the Exception 0 (C) Compiler Error Answer: (C) Explanation: In Java only throwable objects (Throwable objects are instances
1 min read
Java | Exception Handling | Question 2
class Test extends Exception { } class Main { public static void main(String args[]) { try { throw new Test(); } catch(Test t) { System.out.println("Got the Test Exception"); } finally { System.out.println("Inside finally block "); } } } (A) Got the Test Exception Inside finally block (B) Got the Test Exception (C) Inside finall
1 min read
Java | Exception Handling | Question 3
Output of following Java program? class Main { public static void main(String args[]) { int x = 0; int y = 10; int z = y/x; } } (A) Compiler Error (B) Compiles and runs fine (C) Compiles fine but throws ArithmeticException exception Answer: (C) Explanation: ArithmeticException is an unchecked exception, i.e., not checked by the compiler. So the pro
1 min read
Java | Exception Handling | Question 4
class Base extends Exception {} class Derived extends Base {} public class Main { public static void main(String args[]) { // some other stuff try { // Some monitored code throw new Derived(); } catch(Base b) { System.out.println("Caught base class exception"); } catch(Derived d) { System.out.println("Caught derived class exception
1 min read
Java | Exception Handling | Question 8
class Test { public static void main (String[] args) { try { int a = 0; System.out.println ("a = " + a); int b = 20 / a; System.out.println ("b = " + b); } catch(ArithmeticException e) { System.out.println ("Divide by zero error"); } finally { System.out.println ("inside the finally block"); } } } (A) Compile
1 min read
Java | Exception Handling | Question 6
class Test { public static void main(String[] args) { try { int a[]= {1, 2, 3, 4}; for (int i = 1; i <= 4; i++) { System.out.println ("a[" + i + "]=" + a[i] + "\n"); } } catch (Exception e) { System.out.println ("error = " + e); } catch (ArrayIndexOutOfBoundsException e) { System.out.println ("ArrayIn
1 min read
Java | Exception Handling | Question 7
Predict the output of the following program. class Test { String str = "a"; void A() { try { str +="b"; B(); } catch (Exception e) { str += "c"; } } void B() throws Exception { try { str += "d"; C(); } catch(Exception e) { throw new Exception(); } finally { str += "e"; } str += "f"; } void
1 min read
Java | Exception Handling | Question 8
Predict the output of the following program. class Test { int count = 0; void A() throws Exception { try { count++; try { count++; try { count++; throw new Exception(); } catch(Exception ex) { count++; throw new Exception(); } } catch(Exception ex) { count++; } } catch(Exception ex) { count++; } } void display() { System.out.println(count); } publi
1 min read
Exception Propagation in Java
Prerequisite : Exceptions in Java, Checked vs Unchecked Exceptions Exception propagation : An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method. After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "something
3 min read
Exception Handling with Method Overriding in Java
An Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run-time, that disrupts the normal flow of the program’s instructions. Exception handling is used to handle runtime errors. It helps to maintain the normal flow of the program. In any object-oriented programming language, Overriding is a feature t
6 min read
Version Enhancements in Exception Handling introduced in Java SE 7
In this article, the enhancements made by Oracle in version 1.7, along with its implementation, has been discussed. As a part of 1.7 version enhancement, in Exception Handling, the following two concepts have been introduced by Oracle: Try with resources. Multiple catch blocks. Try with resources Until version 1.6, it was highly recommended to writ
4 min read
Java - Exception Handling With Constructors in Inheritance
Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then the child class constructor can throw the same excep
7 min read
User-defined Custom Exception in Java
An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Java provides us the facility to create our own exceptions which are basically derived classes of Exception. Creating
3 min read
Infinity or Exception in Java when divide by 0?
Consider the following code snippets: public class Geeksforgeeks { public static void main(String[] args) { double p = 1; System.out.println(p/0); } } Output: Infinity public class Geeksforgeeks { public static void main(String[] args) { int p = 1; System.out.println(p/0); } } Output: Exception in thread "main" java.lang.ArithmeticException: / by z
1 min read
three90RightbarBannerImg