简单的try catch很简单,但是对于自定义的Exception很多初学者都感到有些头痛,我小总结了下
简单的声明与使用,比如说我们的文件是TestException.java
public class TestException{
public static void main(String[] args){
try{
new abc().abcd();
}catch(Myexception a){
System.out.println(a.getMessage());
}finally{
....
}
}
} //这里是public class的结尾
class Myexception extends Exception{
myexception(String msg) { //构造方法
super(msg) //调用基类的构造方法,将msg信息传递给基类
} //还可以定义其它的构造方法,具体查API文档
}
class abc{
int a,b;
public void abcd() throws Myexception{
if(...){
throw new Myexception("msg") ;//这时抛出一个新的异常,用getMessage()方法可以得到这个信息-----“msg”;
}
}
}
举一个完整的实例
public class Myexception{
public static void main(String[] args){
try{
new chufa().chu(10,0);
}catch(chulingException a){
System.out.println(a.getMessage());
}catch(chufuException b){
System.out.println(b.getMessage());
}finally{
System.out.println("怎么都打印!!!");
}
}
}
class chulingException extends Exception{
chulingException(String msg){
super(msg);
}
}
class chufuException extends Exception{
chufuException(String msg){
super(msg);
}
}
class chufa{
int x,y;
public void chu(int m, int n) throws chulingException,chufuException{
x = m;
y = n;
if(y<0){
throw new chufuException("除数不能为负数");
}else if(y==0){
throw new chulingException("除数不能为0");
}else{
System.out.println(x/y);
}
}
}