在 Java 中,是否可以用一个 catch 代码块来处理多个 try 代码块?
异常是在程序执行期间发生的故障(运行时错误)。当发生异常时程序会立即终止,并且生成异常的那行代码之后的代码永远不会执行。
示例
import java.util.Scanner;
public class ExceptionExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number: ");
int a = sc.nextInt();
System.out.println("Enter second number: ");
int b = sc.nextInt();
int c = a/b;
System.out.println("The result is: "+c);
}
}输出
Enter first number: 100 Enter second number: 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionExample.main(ExceptionExample.java:10)
多个 try 代码块
不能在单个 catch 代码块下使用多个 try 代码块。每个 try 代码块后必须跟 catch 或 finally。仍然可以尝试为多个 try 代码块使用单个 catch 代码块,但会生成编译时错误。
示例
以下 Java 程序尝试在多个 try 代码块下使用单个 catch 代码块。
class ExceptionExample{
public static void main(String args[]) {
int a,b;
try {
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
}
try {
int c=a/b;
System.out.println(c);
}catch(Exception ex) {
System.out.println("Please pass the args while running the program");
}
}
}编译时异常
ExceptionExample.java:4: error: 'try' without 'catch', 'finally' or resource declarations
try {
^
1 error
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP