个性化阅读
专注于IT技术分析

Java 7捕获多个异常

点击下载

本文概述

Java允许你在单个catch块中捕获多个类型异常。它是Java 7中引入的, 有助于优化代码。

你可以使用竖线(|)分隔catch块中的多个异常。

Java 7之前的一种旧方法, 用于处理多个异常。

捕获多个异常类型示例1

public class MultipleExceptionExample{  
	public static void main(String args[]){  
		try{  
			int array[] = newint[10];  
			array[10] = 30/0;  
		}  
		catch(ArithmeticException e){
			System.out.println(e.getMessage());
		}  
		catch(ArrayIndexOutOfBoundsException e){
			System.out.println(e.getMessage());
		}  
		catch(Exception e){
			System.out.println(e.getMessage());
		}  
	 }  
}

输出:

/ by zero

捕获多个异常类型示例2

Java 7为我们提供了什么:

public class MultipleExceptionExample{  
	public static void main(String args[]){  
		try{  
			int array[] = newint[10];  
			array[10] = 30/0;  
		}  
		catch(ArithmeticException | ArrayIndexOutOfBoundsException e){
			System.out.println(e.getMessage());
		}  
	 }  
}

输出:

/ by zero

捕获多个异常类型示例3

public class MultipleExceptionExample{  
	public static void main(String args[]){  
		try{  
			int array[] = newint[10];  
			array[10] = 30/0;  
		}  
		catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsException e){
			System.out.println(e.getMessage());
		}  
	 }  
}

输出:

Compile-time error: The exception ArithmeticException is already caught by the alternative Exception

因此, 在这里, 如果你正在捕获多个异常, 请遵循一般化规则以使其更专业。这意味着, 如果你使用的是超级(通用)类, 请不要使用子(专用)类。

注–处理多个异常类型的catch块使catch参数隐式最终。在上面的示例中, catch参数“ e”是最终的, 因此你不能为其分配任何值。

赞(0)
未经允许不得转载:srcmini » Java 7捕获多个异常

评论 抢沙发

评论前必须登录!