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块必须紧随catch或最后。但是,如果您尝试将单个catch块用于多个try块,则会生成编译时错误。
示例
以下Java程序尝试将单个catch块用于多个try块。
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热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便