try {
// 可能会发生异常的程序代码
} catch (Type1 id1){
// 捕获并处置try抛出的异常类型Type1
}
catch (Type2 id2){
//捕获并处置try抛出的异常类型Type2
}
public class TestException {
public static void main(String[] args) {
int a = 6;
int b = 0;
try { // try监控区域
if (b == 0) throw new ArithmeticException(); // 通过throw语句抛出异常
System.out.println("a/b的值是:" + a / b);
}
catch (ArithmeticException e) { // catch捕捉异常
System.out.println("程序出现异常,变量b不能为0。");
}
System.out.println("程序正常结束。");
}
}
程序出现异常,变量b不能为0。 程序正常结束。
public static void main(String[] args) {
int a = 6;
int b = 0;
try {
System.out.println("a/b的值是:" + a / b);
} catch (ArithmeticException e) {
System.out.println("程序出现异常,变量b不能为0。");
}
System.out.println("程序正常结束。");
}
}
程序出现异常,变量b不能为0。 程序正常结束。
System.out.println(“a/b的值是:” + a/b);
public class TestException {
public static void main(String[] args) {
int a, b;
a = 6;
b = 0; // 除数b 的值为0
System.out.println(a / b);
}
}
Exception in thread “main” java.lang.ArithmeticException: / by zero at Test.TestException.main(TestException.java:8)
public class TestException {
public static void main(String[] args) {
int[] intArray = new int[3];
try {
for (int i = 0; i <= intArray.length; i++) {
intArray[i] = i;
System.out.println("intArray[" + i + "] = " + intArray[i]);
System.out.println("intArray[" + i + "]模 " + (i - 2) + "的值: "
+ intArray[i] % (i - 2));
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("intArray数组下标越界异常。");
} catch (ArithmeticException e) {
System.out.println("除数为0异常。");
}
System.out.println("程序正常结束。");
}
}
intArray[0] = 0 intArray[0]模 -2的值: 0 intArray[1] = 1 intArray[1]模 -1的值: 0 intArray[2] = 2 除数为0异常。 程序正常结束。
catch (ArithmeticException e){
System.out.println("除数为0异常。");
}
try {
// 可能会发生异常的程序代码
} catch (Type1 id1) {
// 捕获并处理try抛出的异常类型Type1
} catch (Type2 id2) {
// 捕获并处理try抛出的异常类型Type2
} finally {
// 无论是否发生异常,都将执行的语句块
}
public class TestException {
public static void main(String args[]) {
int i = 0;
String greetings[] = { " Hello world !", " Hello World !! ",
" HELLO WORLD !!!" };
while (i < 4) {
try {
// 特别注意循环控制变量i的设计,避免造成无限循环
System.out.println(greetings[i++]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界异常");
} finally {
System.out.println("--------------------------");
}
}
}
}
Hello world ! ————————– Hello World !! ————————– HELLO WORLD !!! ————————– 数组下标越界异常 ————————–
try {
System.out.println (greetings[i]); i++;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有