版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Caiaixiong/article/details/85061610
使用throw抛出异常
如果throw语句抛出的异常是Checked异常,则该throw语句要么处于try块里,显式捕获该异常,要么放在一个带throws声明抛出的方法中,即把该异常交给该方法的调用者处理;如果throw语句抛出的异常是Runtime异常,既可以显式捕获该异常,也可以不用理会该异常,把该异常交给调用者处理。
public class ThrowTest {
public static void main(String[] args) {
try {
throwChecked(-3);
} catch (Exception e) {
System.out.println(e.getMessage());
}
throwRuntime(3);
}
public static void throwChecked(int a)throws Exception{
if(a>0){
throw new Exception("a的值大于0,不符合要求");
}
}
public static void throwRuntime(int a){
if(a>0){
throw new RuntimeException("a的值大于0,不符合要求");
}
}
}
自定义异常
定义异常类时通常需要提供两个构造器:一个是无参数的构造器,另一个是带有一个字符串参数的构造器,这个字符串就是异常对象的描述信息。
public class CustomizedException extends Exception{
//无参数的构造器
public CustomizedException(){};
//带一个字符串参数的构造器
public CustomizedException(String msg){
super(msg);
}
}