English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Exception (exception) is a problem that occurs during program execution (runtime error). Here are some example scenarios-
If the size of your array is10If a line of code in the code tries to access the element at11an element.
If you try to divide a number by zero (the result is infinity, and the JVM does not know how to calculate its value).
When an exception occurs, the program will terminate abruptly at the line that caused the exception, preventing the rest of the program from executing. To prevent this, you need to handle exceptions.
Java has two types of exceptions.
Unchecked exceptions - Unchecked exceptions are exceptions that occur at runtime. These are also known as runtime exceptions. They include programming errors, such as logic errors or improper API usage. Runtime exceptions are ignored at compile time.
Checked exceptions - Checked exceptions are exceptions that occur at compile time, also known as compile-time exceptions. These exceptions cannot be simply ignored at compile time. Programmers should pay attention to (handle) these exceptions.
To handle exceptions, Java provides try-Catch block mechanism.
A try is placed around the code that may generate an exception. / Catch block. try / The code in the catch block is called protected code.
try { // Protected code } catch (ExceptionName e1) { // Catch block }
When an exception is thrown within the try block, the JVM stores the exception details in the exception stack and continues to process the catch block instead of terminating the program.
The catch statement involves declaring the type of exception you want to catch. If an exception occurs in the try block, the catch block following the try will be verified.
If an exception type is listed in the catch block, the exception is passed to the catch block in the same way as a parameter is passed to a method argument.
import java.io.File; import java.io.FileInputStream; public class Test { public static void main(String args[]){ System.out.println("Hello"); try { File file = new File("my_file"); FileInputStream fis = new FileInputStream(file); } catch(Exception e) { System.out.println("Cannot find the given file path"); } } }
Output Result
Cannot find the given file path
When caching an exception in a catch block, you can rethrow it using the throw keyword (used to throw an exception object).
When rethrowing an exception, you can throw the same exception without having to adjust it-
try { int result = (arr[a])/(arr[b]); System.out.println("Result ",+arr[a]+"/"+arr[b]+":+result); }catch(ArithmeticException e) { throw e; }
Or, wrap it in a new exception and throw it. When you wrap a cached exception in another exception and throw it, this is called exception chaining or exception wrapping. By doing this, you can adjust your exception and throw a higher-level exception that maintains the abstraction.
try { int result = (arr[a])/(arr[b]); System.out.println("Result ",+arr[a]+"/"+arr[b]+":+result); }catch(ArrayIndexOutOfBoundsException e) { throw new IndexOutOfBoundsException(); }
In the following Java example, the code in demoMethod() may throw ArrayIndexOutOfBoundsException and ArithmeticException. We catch these two exceptions in two different catch blocks.
In the catch block, we throw two exceptions by wrapping them in a higher exception, and the other is thrown directly.
import java.util.Arrays; import java.util.Scanner; public class RethrowExample { public void demoMethod() { Scanner sc = new Scanner(System.in); int[] arr = {10, 20, 30, 2, 0, 8}; System.out.println("Array: ",+Arrays.toString(arr)); System.out.println("Choose numerator and denominator (not 0) from this array (enter positions 0 to 5); int a = sc.nextInt(); int b = sc.nextInt(); try { int result = (arr[a])/(arr[b]); System.out.println("Result ",+arr[a]+"/"+arr[b]+":+result); }catch(ArrayIndexOutOfBoundsException e) { throw new IndexOutOfBoundsException(); }catch(ArithmeticException e) { throw e; } } public static void main(String [] args) { new RethrowExample().demoMethod(); } }
Output Result
Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator (not 0) from this array (enter positions 0 to 5) 0 4 Exception in thread "main" java.lang.ArithmeticException: / divided by zero at myPackage.RethrowExample.demoMethod(RethrowExample.java:16) at myPackage.RethrowExample.main(RethrowExample.java:25)
Output Result
Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator (not 0) from this array (enter positions 0 to 5) 124 5 Exception in thread "main" java.lang.IndexOutOfBoundsException at myPackage.RethrowExample.demoMethod(RethrowExample.java:17) at myPackage.RethrowExample.main(RethrowExample.java:23)