- An exception is a problem that arises during the execution of a program.
- When an Exception occurs the normal flow of the program is disrupted.
- An exception can occur for many different reasons.
- Example:
- A user has entered invalid data.
- A file that needs to be opened cannot be found.
Exception Class:
- All exception classes are subtypes of the java.lang.Exception class.
- The exception class is a subclass of the Throwable class.
- The Exception class has two main subclasses: IOException class and RuntimeException Class.
- We have two categories of Exceptions:
- Checked exceptions:
- A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these are also called compile-time exceptions.
- These exceptions cannot simply be ignored, the programmer should take care of (handle) these exceptions.
- Example:
- ClassNotFoundException - Class not found.
- IllegalAccessException - Access to a class is denied.
- NoSuchMethodException - A requested method does not exist.
- NoSuchFieldException - A requested field does not exist.
- InterruptedException - One thread has been interrupted by another thread.
- Full Example:
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
- Unchecked exceptions −
- An unchecked exception is an exception that occurs at the time of execution.
- These are also called as Runtime Exceptions.
- These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
- Example:
- ArithmeticException: Arithmetic error, such as divide-by-zero.
- ArrayIndexOutOfBoundsException - Array index is out-of-bounds.
- IllegalArgumentException - Illegal argument used to invoke a method.
- IndexOutOfBoundsException- Some type of index is out-of-bounds.
- NullPointerException - Invalid use of a null reference.
- UnsupportedOperationException - An unsupported operation was encountered.
- Full Example:
public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
How to catch exception?
- A method catches an exception using a combination of the try and catch keywords.
- A try/catch block is placed around the code that might generate an exception.
- Code within a try/catch block is referred to as a protected code.
- Syntax:
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
- When an exception occurs, that exception occurred is handled by catch block associated with it.
- Every try block should be immediately followed either by a catch block or finally block.
- Full Example:
public class TryCatch_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
try
{
System.out.println(num[5]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
}
}
- Multiple Catch block
- Syntax:
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
catch (ExceptionName e1) {
// Catch block
}
catch (ExceptionName e1) {
// Catch block
}
- Full Example:
- In this example, array is a size of five elements.
- We are going to initialize index 10 with value 30 divided 0, it may raise exception due to index value.
- The value 30 is divided by zero, again it may raise exception due to divide by zero.
- So, we can handle these kinds of multiple exceptions using multiple catch.
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
- ArithmeticException because we are trying to divide a number by 0.
- ArrayIndexOutOfBoundsException because we have declared a new integer array with array bounds 0 to 4 and we are trying to assign a value to index 10.
- The associativity of the assignment operator = is right to left, so an ArithmeticException is thrown first with the message / by zero.
- In Java SE 7 and later, we can now catch more than one type of exception in a single catch block.
- Each exception type that can be handled by the catch block is separated using a vertical bar or pipe |.
- Syntax:
try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}
- Example:
class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}
Tags:
Core java