例外是程序执行期间发生的问题(运行时错误)。为了理解目的,让我们以不同的方式来看待它。
通常,在编译程序时,如果编译时没有创建.class文件,则该文件是Java中的可执行文件,并且每次执行此.class文件时,它都应成功运行以执行程序中的每一行没有任何问题。但是,在某些特殊情况下,JVM在执行程序时会遇到一些模棱两可的情况,它们不知道该怎么做。
这是一些示例方案-
如果您的数组大小为10,则代码中的一行尝试访问该数组中的第11个元素。
如果您试图将数字除以0(结果为无穷大,并且JVM无法理解如何对其求值)。
通常,当发生异常时,程序会在导致异常的行突然终止,从而使程序的其余部分无法执行。为了防止这种情况,您需要处理异常。
为了处理异常,Java提供了try-catch块机制。
在可能产生异常的代码周围放置了一个try / catch块。try / catch块中的代码称为受保护代码。
try { // Protected code } catch (ExceptionName e1) { // Catch block }
当在try块内引发异常时,JVM终止了异常详细信息,而不是终止程序,将异常详细信息存储在异常堆栈中并进入catch块。
catch语句涉及声明您要捕获的异常类型。如果try块中发生异常,则将其传递到其后的catch块。
如果在catch块中列出了发生的异常类型,则将异常传递到catch块的方式与将参数传递给方法参数的方式一样。
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"); } } }
输出结果
Given file path is not found
finally块位于try块或catch块之后。无论是否发生异常,始终都会执行一个finally代码块。
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"); } } }
输出结果
Exception thrown : java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed