Java 自定义异常

本文通过一个具体的Java程序示例,详细介绍了如何定义自定义异常、如何在方法中抛出异常并进行捕获处理,以及如何使用try-catch-finally结构来确保资源的正确释放。


public class ScaryException extends Exception {

public ScaryException() {
super();
}

public ScaryException(String message) {
super(message);
}

public ScaryException(String message, Throwable cause ) {
super(message, cause);
}

public ScaryException(Throwable cause) {
super(cause);
}

}
public class TestExceptions {

public static void doRisky(String test) throws ScaryException {

System.out.println("start risky......");
//用Object 引用 String 类,是因为 Object 本身是String 类的父类
//拥有 String 类重写的方法。
if ("yes".equals(test)) {
throw new ScaryException();
}
System.out.println("end risky......");
}

public static void main(String[] args) {

String test = "no";
try {
System.out.println("start try......");
doRisky(test);
System.out.println("end try......");
} catch (ScaryException se) {
System.out.println("scary exception");
} finally {
System.out.println("finally......");
}

System.out.println("end of main.");

}

}



class BaseballException extends Exception {}
class Foul extends BaseballException {}
class Strike extends BaseballException {}

abstract class Inning {
public Inning() throws BaseballException {}
public void event() throws BaseballException {

}
public abstract void atBat() throws Strike, Foul;
public void walk() {}
}

class StormException extends Exception {}
class RainedOut extends StormException {}
class PopFoul extends Foul {}

interface Storm {
public void event();
public void rainHard() throws RainedOut;
}

public class StormyInning extends Inning implements Storm {
// 构造函数可以添加新的异常,但是必须处理父类的异常
public StormyInning() throws RainedOut, BaseballException {
}

public StormyInning(String s) throws Foul, BaseballException {
}
/* 父类的方法没有异常的不能添加异常
public void walk() throws PopFoul {

}*/
// 接口不能为父类中存在的方法添加异常
public void event() {

}


@Override
public void rainHard() throws RainedOut {
// TODO Auto-generated method stub

}
// 可以窄化抛出的异常 PopFoul 可以用来替换 Strike, Foul
@Override
public void atBat() throws Strike, Foul {
// TODO Auto-generated method stub

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值