Tutorials

Java Exception Handling


Unchecked Exception


Unchecked exception occurs as a result of error in programming logic.

Compiler fails to detect and warn about an unchecked exception present in code.

 

Unchecked Exceptions extends java.lang.RuntimeException

For example, if you try to divide a number by 0 (zero) or want to access value from certain index that doesnot exists in array. These kind of logical error will only be caught at runtime.

 

Example

  • ArithmeticException
  • ArrayIndexOutOfBoundException
  • NullPointerExceptions

How to handle Unchecked Exception?

As a programmer you need to make sure that you code your logics accurately. 

If you write code like,

 

int a= 10;

int b= 0;

int res = a/b;   //logical error - division by 0

 

In case you write such codes then you will get error at runtime and would have to debug the code and locate the line which throws the error and fix it.

So if you write logic accurately you can avoid unchecked exception from occurence.

 

Example 1: Performing division by 0


package exceptionHandling;

public class TIHException {

      public static void main(String[] args) {

            int firstNum = 19;
            int secNum = 0;           

            int div = firstNum/secNum; //logical error

      }

}

OUTPUT:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at exceptionHandling.TIHException.main(TIHException.java:9)
 

 

Example 2: Accessing index which doesn't exists

package exceptionHandling;

public class TIHException {

    public static void main(String[] args) {

    int arr[] = {1,2,3,4,5};
    System.out.println(arr[10]); //illogical code

    }

}

OUTPUT:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at exceptionHandling.TIHException.main(TIHException.java:13)
 


Please Share this page
Views : 69
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!