Unchecked exception in java

Unchecked exception in java is the exception that is not checked at the compiled time. The compiler is not able to recognize these exceptions at compile time. An unchecked exception in java occurs at the time of execution, so they are also called Runtime Exceptions. For example NullPointerException, ArithmeticException, ArrayIndexOutOfBound, logic error, etc.

unchecked exception example

Lets us take an example of unchecked exception or runtime exception. In this example, we are trying to print some strings and doing some operations on it. So, we are creating a class UncheckedExceptionExample and after that, we are printing some names and append the strings.

Unchecked exception in java
class UncheckedExceptionExample 
{ 
     public static void main(String[] args) 
     { 
	String a = "Ravi";
	String b = "Ram";
	String c = null;
		
	// Now print all the strings
	System.out.println("First name = " +a);
	System.out.println("Second name = " +b);
	System.out.println("Third name = " +c);
		
	// concatenating string 
	System.out.println("Concatenation of String = " + c.concat(a));
    }
}

Output: First name = Ravi Second name = Ram Third name = null Exception in thread “main” java.lang.NullPointerException at UncheckedExceptionExample.main(UncheckedExceptionExample.java:14)

Explanation of example: NullPointerException is thrown by the compiler at runtime time. Because we declare a String reference variable that was pointing to null. We can’t call any method by use of null. So, this program throws NullPointerException.

We can resolve this problem we have two solutions:

  1. By using throws (Discuss it later)
  2. By use a try-catch block.

We can resolve this problem by using a try-catch block. So, we need to put the code in a try block and catch the exception in the catch block.

class UncheckedExceptionExample 
{ 
  public static void main(String[] args) 
  { 
    String a = "Ravi";
    String b = "Ram";
    String c = null;
    try
    {
	// Now print all the strings
	System.out.println("First name = " +a);
	System.out.println("Second name = " +b);
	System.out.println("Third name = " +c);
		
	// concating string 
	System.out.println("Concatination of String = " + c.concat(a));
    }
    catch(NullPointerException e)
    {
	System.out.print("NullPointerException exception is occured"); 
    }
  }
}

Output: First name = Ravi
Second name = Ram
Third name = null
NullPointerException exception is occured

Leave a Comment