1、写一个自定义的异常类(MyException),让其继承Exception.
public class MyException extends Exception {
static final long serialVersionUID = -3387516993124229948L;
public MyException() {
}
public MyException(String s){
super(s);
}
}
2、分析super(s)(这里只是源码解析,看得懂就看,看不懂就到第三步)
public class Exception extends Throwable {
static final long serialVersionUID = -3387516993124229948L;
public Exception(String message) {
super(message);
}
}
public class Throwable implements Serializable {
private static final long serialVersionUID = -3042686055658047285L;
private String detailMessage;
private transient Object backtrace;
private StackTraceElement[] stackTrace = UNASSIGNED_STACK;
private native Throwable fillInStackTrace(int dummy);
private static final StackTraceElement[] UNASSIGNED_STACK
= new StackTraceElement[0];
public synchronized Throwable fillInStackTrace() {
if (stackTrace != null ||
backtrace != null /* Out of protocol state */ ) {
fillInStackTrace(0);
stackTrace = UNASSIGNED_STACK;
}
return this;
}
public Throwable(String message) {
fillInStackTrace();
detailMessage = message;
}
}
public final class StackTraceElement implements java.io.Serializable {
// Normally initialized by VM (public constructor added in 1.5)
private String declaringClass;
private String methodName;
private String fileName;
private int lineNumber;
}
3、写一个方法里面抛出自己的异常
public class Height {
private int maxHeight=200;
private int minHeight=145;
/**
*
* @param stature 身高
* @throws MyException
*/
public void check(int stature) throws MyException {
if (stature > maxHeight || stature < minHeight) {
//身高不在正常范围时抛出异常
throw new MyException("身高不正常,身高应该是145--200之间");
} else {
System.out.println("身高正常,你的身高是" + stature);
}
}
}
4、写一个测试方法(抛出异常)
public class HeightTest {
public static void main(String[] args) {
int height=100;
Height hei=new Height();
try{
hei.check(height);
} catch (MyException e) {
e.printStackTrace();
}
}
}