Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does unchecked exception mean in java

Tags:

java

exception

Well, from a book i got the below lines:

Java defines several exception classes inside the standard package java.lang. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available.

Furthermore, they need not to be included in any method's throws list.

So, doesnt it mean that i dont need a try catch block?

i have done the following code, but it showing error:

 Exception in thread "main" java.lang.ArithmeticException: / by zero
at ArithCls.main(ArithCls.java:10)

Code:

import java.lang.*;
public class ArithCls {

public static void main(String[] args)
    {
    int a=20;
    int b=0;
    int c = a/b;
    System.out.println("After code");
}
}
like image 443
Shaon Hasan Avatar asked Sep 17 '26 14:09

Shaon Hasan


2 Answers

An Unchecked Exception is one that is not checked ;-P

No, in all seriousness, it's an exception that the compiler/jvm does not force your code to check for. These are generally (always?) a runtime exception, such as NullPointerException.

A runtime exception is generally an exception that you can't properly anticipate and/or handle before execution time -- and therefore it will crash your program's execution.

You, in your own code, can explicitly "check" for them by using a try/catch block, however generally it's better practice to handle these via null checks, etc.

if (str != null) {

    // do stuff
}
like image 198
SnakeDoc Avatar answered Sep 19 '26 04:09

SnakeDoc


An unchecked exception does not need to be declared or surrounded by a try-catch clause, as opposed to checked exceptions.

If you look at the Javadoc, you can see that the inheritance tree for ArithmeticException is as follows:

java.lang.Object
    java.lang.Throwable
        java.lang.Exception
            java.lang.RuntimeException
                java.lang.ArithmeticException

So, it is a subclass of RuntimeException, and therefore an unchecked exception. Unchecked exceptions are RuntimeException, Error, and all their subclasses.

You can read more about the different types of exceptions in the Java tutorials.

like image 38
Keppil Avatar answered Sep 19 '26 03:09

Keppil