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");
}
}
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With