java151227ExceptionDemo2

本文详细介绍了Java中使用try-catch-finally结构处理异常,特别关注了如何自定义异常类来处理特定场景的错误情况。通过示例演示了如何在`Demo2`类中定义`FuShuException`类来捕获并处理输入参数为负数的情况。
package java151227;


public class ExceptionDemo2 {
public static void main(String[] args) {


Demo2 demo2 = new Demo2();
try {
int x = demo2.div(4, -1);
System.out.println("x=" + x);
} catch (FuShuException e) {
System.out.println("出现负数!");
System.out.println(e.toString());
// return;
}finally {
System.out.println("finally");
}
System.out.println("over");
}


}


class Demo2 {
int div(int a, int b) throws FuShuException {
if (b < 0) {
throw new FuShuException("出现负数!");
}
return a / b;


}
}




class FuShuException extends java.lang.Exception {
// private String msgString;
// FuShuException(String msgString) {
// this.msgString=msgString;
// }
// @Override
// public String getMessage(){
// return msgString;
//
// }
public FuShuException(String msg) {
super(msg);
}


}


//class Throwable {
// private String message;
//
// public Throwable(String msgString) {
// this.message = msgString;
// }
//
// public String getMessage() {
// return message;
//
// }
//}
//
//class Exception extends java151222.Throwable {
//
// public Exception(String msgString) {
// super(msgString);
//
// }
//
//}


//class Person {
//
// String name;
//
// public Person(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
//
// }
//}
//
//class Student extends java151222.Person {
//
// public Student(String name) {
// super(name);
// }
//
//}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值