English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Exceptions are problems that occur during program execution (runtime errors). To understand the purpose, let's look at it in a different way.
Generally, when compiling a program, if no .class file is created during compilation, the file is an executable file in Java, and it should run successfully every time the .class file is executed to execute each line of the program without any problems. However, in some special cases, the JVM encounters some ambiguous situations during program execution, which it does not know how to handle.
Here are some example solutions-
If the size of your array is10If a line of code in the code attempts to access the element at index11elements.
If you try to divide a number by zero (resulting in infinity, and the JVM cannot understand how to evaluate it).
Generally, when an exception occurs, the program suddenly terminates at the line that caused the exception, preventing the rest of the program from executing. To prevent this, you need to handle 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 terminates the exception details instead of terminating the program, stores the exception details in the exception stack, and enters the catch block.
The catch statement involves declaring the type of exception you want to catch. If an exception occurs in the try block, it is passed to the catch block that follows.
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("Given file path is not found"); } } }
Output result
Given file path is not found
The finally block is located after the try block or catch block. Regardless of whether an exception occurs, a finally code block will always be executed.
public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three:") + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown:") + e); }finally { a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } }
Output result
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed