public class ExceptionDemo {
public static void main(String[] args) {
//OutOfMemoryError内存溢出错误,
int[] i = new int[1024*1024*1024];
System.out.println(i[1]);
//ArrayIndexOutOfBoundsException索引越界异常
int[] s = new int[2];
System.out.println(s[2]);
Calc calc = new Calc();
//假如我们在这里捕获异常
try {
calc.run(4, 0);
calc.run(4, -1);
} catch (NegativeException e) {//必须先抛出异常的自定义子类
e.printStackTrace();
System.out.println(e.getMessage());
//throw e;//可以继续将此异常抛出
} catch (ArithmeticException e){//抛出自定义异常类的父类
e.printStackTrace();
System.out.println(e.getMessage());
//throw e;
} finally {
System.out.println("finally肯定会执行到");
}
//如果上面进行了异常捕获,那么代码可以继续执行,否者代码不能继续执行
System.out.println("可以执行到!");
try {
calc.run(4, -1);
} catch (NegativeException e) {
e.printStackTrace();
System.out.println(e.getMessage());
return;
} finally {
System.out.println("肯定会执行的");
}
System.out.println("执行不到了");//执行不到此行代码
}
}
/**
* 自定义异常
*/
class NegativeException extends ArithmeticException{
public NegativeException() {
}
public NegativeException(String msg) {
super(msg);
}
}
interface AA{
public abstract void method();
}
class Calc implements AA{
//ArithmeticException其实为运行时异常(RuntimeException),即使不进行throws声明,也可以通过编译
public int run(int m,int n)throws ArithmeticException,NegativeException{
if(n==0){
throw new ArithmeticException("除数不能为0");
}else if(n<0){
throw new NegativeException("除数不能为负数");
}
int s = m/n;
return s ;
}
@Override
public void method() {
try {
int p = 4/0;
} catch (ArithmeticException e) {
e.printStackTrace();
throw new RuntimeException();//将异常继续抛出为运行时异常
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有