Java基础——异常的捕获与抛出
前言:
- Error类(错误)和Exception类(异常)是Throwable类的子类。
- 异常分为CheckedException类(编译时异常)和RuntimeException类(运行时异常)。
- CheckedException类(编译时异常)必须提前处理。
- RuntimeException类(运行时异常)可选择性处理
一、捕获异常;
规则:
try()
里的代码A或代码B只要有一个出现异常就会运行catch()
里的代码C。- 无论是否有异常都会运行
finally
里的代码D。 - 假如要捕获多个异常,要从小到大。
格式:
try
{
待捕获代码A
待捕获代码B
}
catch(想要捕获的异常类型 对象名)
{
异常被捕获时的输出代码C
}
finally
{
代码D
}
后续代码
例如:
int m=2, n=0;
try
{
System.out.println(m/n);
}
catch(Exception e)
{
System.out.println("除数不能为0");
}
catch(Throwable t)
{
System.out.println("Throwable");
}
finally
{
System.out.println("finally");
}
编译结果:
除数不能为0
finally
二、抛出异常;
规则:
- 当判断方法存在异常时先通过关键字
throws
抛出方法异常。 - 然后可以选择在主函数中选择捕获异常或继续抛出异常。
例一:捕获异常
public static void main(String[] args)
{
try
{
int a=num(4,0);
System.out.println(a);
}
catch(Exception e)
{
e.printStackTrace(); //在命令行打印异常信息在程序中出错的位置及原因。
System.out.println("除数不能为0");
}
}
public static int num(int x,int y)throws Exception
{
int result = x/y;
return result;
}
编译结果:
java.lang.ArithmeticException: / by zero
at 源代码.Example.num(Example.java:22)
at 源代码.Example.main(Example.java:10)
除数不能为0
例二:双重抛出异常
public static void main(String[] args)throws Exception
{
num();
}
public static void num()throws Exception
{
int x=4, y=0;
int m=x/y;
System.out.println(m);
}
编译结果:
Exception in thread "main" java.lang.ArithmeticException: / by zero
例三:主动双重抛出异常
public static void main(String[] args)throws Exception
{
num();
}
public static void num()throws Exception
{
int x=4, y=0;
if(y==0)
{
throw new Exception("除数不能为0");
}
int m=x/y;
System.out.println(m);
}
编译结果:
Exception in thread "main" java.lang.Exception: 除数不能为0
三、自定义异常;
规则:
- 定义自定义异常类,继承至
Exception
类,重写其中的两个构造方法。 - 在异常所在方法的后面添加
throws
语句,表示该方法有一个自定义异常类型的异常信息需要处理。 - 通过if语句设置条件,确定需要抛出异常的位置,使用
throw
语句抛出自定义异常类的实例。
格式:
class 自定义异常名 extends Exception
{
public 自定义异常名()
{
}
public 自定义异常名(String msg)
{
super(msg);
}
}
例如:
public class Student
{
public static void main(String[] args)throws MyException
{
String username ="巴提";
if(username.length()<3)
{
throw new MyException("用户名小于三位");
}
System.out.println("用户名格式正确");
}
}
class MyException extends Exception
{
public MyException()
{
}
public MyException(String msg)
{
super(msg);
}
}
编译结果:
源代码.MyException: 用户名小于三位