1:Exception(String message): Constructs a new exception with the specified detail message
//此为异常类Exception的一个构造方法。该方法用于自定义异常类时使用。
自定义一个异常类:(举例)
public class MyException extends Exception {
private int id;
MyException(String s,int id) {
super(s);//这个地方就是用了上述提到的Exception(String message): 构造方法。
this.id = id;
}
}
2:public class Test {
public void regist(int num) throws MyException {
if(num < 0) {
throw new MyException("登记人数为负值!",3);
}
System.out.println("登记人数为:" + num);
}
public void manager() {
try {
regist(-1);
} catch(MyException e) {
System.out.println("登记失败,出错类型码为:"+ e.getId());
e.printStackTrace();
}
System.out.println("操作结束!");
}
public static void main(String[] args) {
Test t = new Test();
t.manager();
}
}
//Dos下的显示如图:
MyException:登记人数为负值!是e.printStackTrace();造成的。输出的内容为throw new MyException("登记人数为负值!",3);注意:printStackTrace();为把堆栈内的所有信息都打印出来。
public void manager() {
try {
regist(-1);
} catch(MyException e) {
e.printStackTrace();
System.out.println("登记失败,出错类型码为:"+ e.getId());
}
System.out.println("操作结束!");
}
注意:如果把粗体的部分像上述代码颠倒放置,则Dos下异常显示顺序为:
3:对于try catch finally执行的一些理解:
有finally和没有finally的区别。
如果在try语句块内存在return语句,finally子句中的代码会在返回前执行。
如果catch语句中有return语句,则如果不加finally,则不会被执行。如:
public class TestFinal {
public static void main(String[] args) {
TestFinal me = new TestFinal();
try {
me.m();
} catch(Exception e) {
e.printStackTrace();
return;
}
finally {
System.out.println("嘿嘿……");
}
}
public void m() throws Exception {
throw new Exception("出错啦,呵呵……");
}
}//如果加finally,则会执行System.out.println("嘿嘿……");
如果不加finally,则System.out.println("嘿嘿……");不会被执行。总之如果异常处理之后还有别的语句想要被执行,则最好是要加上finally语句。