public int myPlus(int a, int b) throws Exception { int res = a + b; if (res > 30) }
sorry, clicked the wrong button. public int myPlus(int a, int b) throws Exception { int res = a + b; if (res > 30) throw new Exception("Greater than 30."); return res; }
thank 杉叶,因为没有看到关于catch自己异常的例子,所以很不明白。看过别人自定义的异常,大都是在调用中throw 自己的异常,其实前面还是加上自己的判断。只不过封装了一些msgId和msg而已。 其实在程序中加入if a < 30 then判断也是可以的,但是如果代码多了(例如好几个模块),当30变成50的时候,修改的工作量很大,而且也不好管理。我只是随手想的个例子,其实可以把30,50这样的数置为系统值也可以。抛开讨论这个自定义异常的好处。一般情况下,如果捕捉的?“一般异常的处理原则是在基类里面抛出到调用的类里面”能不能给点代码看看,或者有个连接也好。 //bow
thank hayai,我忘了贴一下我的代码。大家不要笑我啊,呵呵,very少的代码。 //----------------------自定义的Exception--------------// import java.lang.Exception;public class MyException extends Exception { private int msgId = 0; private String msg = "";
public MyException(int a, String b) throws Exception{ msgId = a; msg = b; throw new Exception(); } } //--------------自定义的MyClass.java------------// public class myClass { public int myPlus(int a, int b) throws Exception{ if ((a+b) < 30) { return a+b; } else { throw new myException(1, "larger than 30"); } } //end of myPlus method } //---------调用类--------------------------// import java.lang.Integer;public class test { public static void main(String[] args) throws Exception { myClass aa = new myClass(); int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = 0; try { c = aa.myPlus(a, b); System.out.println(c); } catch (myException e) { System.out.println("Catch my def exception"); } } //end of main }
方法一:最简单直接的办法 throw new Exception("Greater than 30."); 方法二:自己定义异常类 例如楼上那位兄弟的做法
throws Exception
{
int res = a + b;
if (res > 30)
}
public int myPlus(int a, int b)
throws Exception
{
int res = a + b;
if (res > 30)
throw new Exception("Greater than 30.");
return res;
}
其实在程序中加入if a < 30 then判断也是可以的,但是如果代码多了(例如好几个模块),当30变成50的时候,修改的工作量很大,而且也不好管理。我只是随手想的个例子,其实可以把30,50这样的数置为系统值也可以。抛开讨论这个自定义异常的好处。一般情况下,如果捕捉的?“一般异常的处理原则是在基类里面抛出到调用的类里面”能不能给点代码看看,或者有个连接也好。
//bow
//----------------------自定义的Exception--------------//
import java.lang.Exception;public class MyException extends Exception {
private int msgId = 0;
private String msg = "";
public MyException(int a, String b) throws Exception{
msgId = a;
msg = b;
throw new Exception();
}
}
//--------------自定义的MyClass.java------------//
public class myClass {
public int myPlus(int a, int b) throws Exception{
if ((a+b) < 30) {
return a+b;
} else {
throw new myException(1, "larger than 30");
}
} //end of myPlus method
}
//---------调用类--------------------------//
import java.lang.Integer;public class test {
public static void main(String[] args) throws Exception {
myClass aa = new myClass();
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = 0;
try {
c = aa.myPlus(a, b);
System.out.println(c);
}
catch (myException e) {
System.out.println("Catch my def exception");
}
} //end of main
}
throw new Exception("Greater than 30.");
方法二:自己定义异常类
例如楼上那位兄弟的做法