Java异常小总结
- 异常的介绍
- 异常的分类
- 异常的处理以及自定义异常
异常的介绍
异常的分类
解决的办法:
整体的架构图:
异常的处理以及自定义异常
再看一个finally的使用例子:
public class ReturnExceptionDemo {
public static void methodA(){
try {
System.out.println("进入方法A!");
throw new RuntimeException("在方法A中制造异常!");
}finally {
System.out.println("执行方法A中的finally!");
}
}
public static int methodB(){
try {
System.out.println("进入方法B!");
return 1;
} finally {
System.out.println("执行方法B中的finally!");
return 2;
}
}
public static void main(String[] args) {
try {
methodA();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(methodB());
}
}
输出:
还有一个关于自定义异常的一个案例:
扫描二维码关注公众号,回复:
3272953 查看本文章
public class EcmDefDemo {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
try {
// int a = cin.nextInt();
// int b = cin.nextInt();
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
ecm(a,b); //执行除法
}catch (NumberFormatException e) {
System.out.println("输入的数据类型不一致....");
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("缺少了输入数据.....");
}
catch (ArithmeticException e) {
System.out.println("分母为0了.....");
}
catch (DefException e) {
System.out.println(e.getMessage());
}
}
//判断是否输入负数,如果输入了,就抛出一个异常
public static void ecm (int a,int b) throws DefException {
if(a < 0 || b < 0){
throw new DefException("你输入的数值存在负数.....");
}
System.out.println(a / b);
}
}
class DefException extends Exception{
static final long serialVersionUID = -33873124229948L;
public DefException() {
}
public DefException(String message) {
super(message);
}
}