Exceptions in Java
Exceptions in Java
What is an exception?
An exception is an abnormal condition that changes the
Types of Exception?
Types of Exception
1) Checked Exception
Checked exceptions are checked at compile-time. The classes that
extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException
etc.
2) Unchecked Exception
The classes that extend RuntimeException are known as
unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time.
3) Error
Errors are not possible to handle in your program code
Exception Hierarchy
handling.
try
catch
finally
throw
throws
try Block
Java try block is used to enclose the code that might
catch Block
Java catch block is used to handle the Exception. It
finally Block
Java finally block is a block that is used to execute
Example of try-catch-finally
public class Test {
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{System.out.println(e);}
finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
throw keyword
The Java throw keyword is used to explicitly throw
an exception.
We can throw either checked or uncheked exception
in java by throw keyword. The throw keyword is
mainly used to throw custom exception.
Syntax of java throw keyword is given below.
throw exception;
throws
declare an exception.
signature.
e.g.
public void method()throws
IOException,SQLException.
If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class Child extends Parent{
void msg()throws ArithmeticException{System.out.println("child");}
public static void main(String args[]){
Parent p=new Child();
try{
p.msg();
}catch(Exception e){}
}
}
Custom Exception
If you are creating your own Exception that is known as custom
Thank You