开发手册 欢迎您!
软件开发者资料库

Java try catch finally异常处理(Exception)

Java中try块可以捕获测试代码块中的错误。catch块可以处理错误。finally块无论是否try和catch块出现异常都可以执行代码。本文主要介绍Java try catch finally异常处理(Exception)。

1、Java Exceptions

执行Java代码时,可能会发生不同的错误异常:程序员编写的编码错误,由于输入错误引起的错误或其他不可预见的情况。

发生错误时,Java通常会停止并生成错误消息。 技术术语是:Java将引发异常(引发错误)。

2、Java try  catch

try语句允许定义要执行的错误代码块。

如果在try块中发生错误,则catch语句允许定义要执行的代码块。

trycatch关键字成对出现:

语法

try {  //  要尝试的代码块}catch(Exception e) {  //  处理错误的代码块}

考虑以下示例:

这将产生一个错误,因为myNumbers [10]不存在。输出将是这样的:

public class Main {  public static void main(String[ ] args) {    int[] myNumbers = {1, 2, 3};    System.out.println(myNumbers[8]); // 不存在会报错!  }}

如果发生错误,我们可以使用try catch来捕获错误并执行一些代码来处理该错误:

例如:

public class Main {  public static void main(String[ ] args) {    try {      int[] myNumbers = {1, 2, 3};      System.out.println(myNumbers[8]);    } catch (Exception e) {      System.out.println("输出异常信息等其它操作");    }  }}

3、finally

finally语句可以在try catch之后执行代码,而不管是否在try代码中出现异常:

例如:

public class Main {  public static void main(String[] args) {    try {      int[] myNumbers = {1, 2, 3};      System.out.println(myNumbers[8]);    } catch (Exception e) {      System.out.println("输出异常信息等其它操作");
    } finally {      System.out.println("执行资源释放等相关代码");    }  }}

4、throw关键字

throw语句用于创建抛出自定义错误。

throw语句与异常类型一起使用。 Java中提供了许多异常类型:ArithmeticExceptionFileNotFoundExceptionArrayIndexOutOfBoundsExceptionSecurityException等:

例如:

public class Main {  static void checkValue(int x) {    if (x < 0) {      throw new ArithmeticException("error is x < 0");    }    else {      System.out.println("x > 0");    }  }  public static void main(String[] args) {    checkValue(15);   }}
public class DemoThrow {    public static void main(String[] args) {      int a =   DemoThrow.div(4,0);      System.out.println(a);    }    public static int div(int a,int b)      {            if(b==0)              throw new ArithmeticException("异常信息:除数不能为0");//抛出具体问题,编译时不检测            return a/b;     }}

5、throws 关键字

throws关键字说明方法可能抛出的异常类型。

Java中有许多可用的异常类型:ArithmeticExceptionClassNotFoundExceptionArrayIndexOutOfBoundsExceptionSecurityException等。

例如:

publicclassExample{     publicstaticvoidmain(String[] args){              try {         int    result = divide(4,2);          System.out.println(result);       } catch (Exception e) {                  e.printStackTrace();       }          }        publicstaticintdivide(int x,int y)throws Exception    {        int result = x/y;        return result;    } }

throw和throws之间的区别:

throw

throws

用于引发方法的异常

用于指示方法可能抛出的异常类型

不能抛出多个异常

可以声明多个异常