java异常处理的简单实例和解释,自定义一个异常类

JAVA中异常处理的关健字有
1:try catch
try catch是这之间所包含的代码如果出现异常时捉住它,并进处得理,如果代码之间有错误,不会影响程序继续执行下去,程序会继续往后执行。
2:throw
是在程序中明确引发的异常,比如throw new Exception();
3:throws
表明方法可能会引发异常,在方法内部并不处理这个异常,想要得到异常的话,调用者使用try catch语句即可得到
4:finally
不管有没有异常程序段中都会被执行的代码
下面直接看一个实例:
public class CatchClass {
public static double numberOp(String number1, String number2)
throws Exception {
if (number1 == null || number2 == null) {
throw new Exception("数字不能为空");
}
double n1 = 0;
double n2 = 0;
double result = 0;

n1 = Double.valueOf(number1);
n2 = Double.valueOf(number2);
result = n1 / n2;

return result;
}

public static void main(String[] args) {
//捕获到throw出的异常
try {
double n = CatchClass.numberOp(null, "0");
} catch (Exception e) {
System.out.println(e.toString());
}
//捕获到程序本身的异常
try {
double n = CatchClass.numberOp("ss", "0");
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
打印出结果:
java.lang.Exception: 数字不能为空
java.lang.NumberFormatException: For input string: "ss"

自定义一个异常类:
有时候的异常太过于广泛,我们需要更精细化的定义异常就需要用到自定义异常类了。
public class CatchClass extends Exception {
int number;

CatchClass(int number) throws Exception {
//根据number的值给出不同的异常信息,这里只是一个简单的实例,复杂的也是一个道 理,根 据给的值不同,自定义给出异常的信息
this.number = number;
if(number < 0) throw new Exception("数字必须大于0");
}
//测试方法
public static void main(String[] args) throws CatchClass {
try {
CatchClass CatchClass = new CatchClass(-1);
} catch (Exception e) {
System.out.print(e.toString());
}
}
}

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值