Java中关于异常的一些问题(一)

来源:互联网 发布:golang time.after 编辑:程序博客网 时间:2024/05/24 05:57

关键字:try,catch,finally,throw,throws

使用格式:

try{}catch{};
//可以有多个catch块
<pre name="code" class="java">try{}catch{}catch{}catch{}


注:try和catch 后的括号不可以省略,即使他们后面只有一行代码。

三种常见的运行时异常IndexOutOfBoundsException(数组越界)、NumberFormatException(数字格式异常)、ArithmeticException(算术异常)。

异常捕获时,一定要记住先捕获小异常,再捕获大异常,所以父类异常的catch块都应该排在子类异常catch快的后面。

public class DivTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubtry{int a = Integer.parseInt(args[0]);int b = Integer.parseInt(args[1]);int c = a / b;System.out.println("你输入的两个数相除的结果是:" + c);}catch(IndexOutOfBoundsException ie){System.out.println("数组越界:运行时输入的参数个数不够");}catch(NumberFormatException ne){System.out.println("数字格式异常:程序只能接收整数参数");}catch(ArithmeticException ae){System.out.println("算术异常");}catch(Exception e){System.out.println("未知异常");}}}

所有的异常对象都是Exception或其子类的实例。


从Java7开始,一个catch块可以捕获多种类型的异常,但需要注意以下两点:

1、多种异常类型之间用竖线(|)隔开

2、异常变量有隐式的final修饰,以此程序不能对异常变量重新赋值

public class MultiExceptionTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubtry{int a = Integer.parseInt(args[0]);int b = Integer.parseInt(args[1]);int c = a / b;System.out.println("你输入的两个数相除的结果是:" + c);}catch(IndexOutOfBoundsException|NumberFormatException|ArithmeticException ie){System.out.println("程序发生了数组越界、数字格式异常、算术异常之一");//捕获多异常时,异常变量默认有final修饰//所以下面代码有错//ie = new ArithmeticException("test");}catch(Exception e){System.out.println("未知异常");//捕获一种异常时,异常变量没有final修饰//所以下面的代码正确e = new RuntimeException("test");}}}



0 0