Exception is a class. Whenever an exception happens, the JVM will create an instance of a class and it will throw that exception.
Exceptions are occurred in situations like your program run out of the memory , file does not exist in the given path , network connections are dropped etc. we can say it as Runtime Errors occurs during the execution of a program that disrupts the normal flow of instructions.
Errors cannot handled by our program, like OutOfMemoryError
checked exception vs unchecked exception
compile time - checked exception:
must be handled explicitly by the code
not following syntactical rules
a try/catch block / a "throws"
(to indicate that the method might throw this type of exception which must be handled in the calling class or above).
runtime exception - unchecked exception:
does not need to be handled explicitly
Generally RuntimeExceptions are exceptions that can be prevented by code. E.gNullPointerException
,ArrayIndexOutOfBoundException
.
Try...catch
class TestClass
{
public static void main (String[] args)
{
try{
int value=10/0;//an integer "divide by zero" throws exception
}catch(ArithmeticException ea){
System.out.println(ea);
//you can handle exception in this block
System.out.println("Exception Handle here !!");
}
System.out.println("next line...");
}
}
output:
java.lang.ArithmeticException: / by zero
Exception Handle here !!
next line...
Here you can see the exception handled in the catch block and the program continue to next line. It is important to note that Java try block must be followed by either catch or finally block.
Finally
class TestClass
{
public static void main (String[] args)
{
try{
int value=10/2;
System.out.println("Result is: " + value);
}catch(ArithmeticException ea){
System.out.println(ea);
}
finally{
System.out.println("Finally should execute !!");
}
}
}
It is not mandatory to include a finally block at all, but if you do, it will run regardless of whether an exception was thrown and handled by the try and catch parts of the block. In normal case execution the finally block is executed after try block. When any exception occurs, first the catch block is executed and then finally block is executed.
syntax
try {
//statements that may cause an exception
}
finally{
//statements to be executed
}
catch multiple exception
try {
//Do some processing which throws exceptions
} catch(SQLException IOException e) {
someCode();
} catch(Exception e) {
someCode();
}
Throws
a method signature
the method is not going to handle the checked exception but the caller needs to handle it.
And if at the end nobody handles it, everybody declares it using throws, it will go to the JVM's default exception handler.
Throw
statement to throw objectt
wheret instanceof java.lang.Throwable
must be true.
usually throw a runtime exception