标签:编程 抛出异常 ring 运行时 time rgs 异常处理 exti 显示
public static void main(String[] args) {
int[] i = {1,2,3};
try {
i[3] = 10;
int j= 2/0;
System.out.println("try中异常代码之后部分不会执行");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("发生了数组越界");
} catch (ArithmeticException e) {
System.out.println("发生了被除数为0");
} finally {
System.out.println("finally代码运行正常"); // finally 中代码永远会执行
}
System.out.println("try之后的代码运行正常");
}
public static void main(String arg[]) {
try {
function();
} catch (ArrayIndexOutOfBoundsException e){
System.out.println("e = " + e.toString());
} finally {
System.out.println("finally");
}
}
public static void function() throws ArrayIndexOutOfBoundsException{
int a, b;
Scanner in = new Scanner(System.in);
a = in.nextInt();
b = in.nextInt();
int c = a / b;
System.out.println(c);
int[] a1 = { 1, 3, 3 };
System.out.println(a1[3]);
System.out.println("异常后的语句");
}
finally块不管异常是否发生,只要对应的try执行了,则它一定也执行。只有一种方法让finally块不执行:System.exit()。因此finally块通常用来做资源释放操作:关闭文件,关闭数据库连接等等。
良好的编程习惯是:在try块中打开资源,在finally块中清理释放这些资源。
这是正常的情况,但是也有特例。关于finally有很多恶心,偏、怪、难的问题,我在本文最后统一介绍了,电梯速达->:finally块和return
public class MyException extends Exception {
public MyException(){
}
public MyException(String message){
super(message);
}
}
// test
public static void main(String[] args) throws MyException {
List<String> list = new ArrayList<>();
list.add("男");
list.add("女");
if(!list.contains("中性")){
throw new MyException("性格不合适");
}
}
public class MyRuntime extends RuntimeException{
public MyRuntime(){
super();
}
public MyRuntime(String message){
super(message);
}
// test
public static void main(String[] args) throws MyException {
try{
throw new MyRuntime("a runtime exception!");
} catch (MyRuntime myRuntime){
System.out.println("myRuntime = " + myRuntime);
}
}
标签:编程 抛出异常 ring 运行时 time rgs 异常处理 exti 显示
原文地址:https://www.cnblogs.com/xiongyungang/p/12506248.html