有没有一种方法可以获得异常编号来更好地控制所发生的事情?
例如:
try
{ Do some work
}
catch(Exception e)
{ if(e.**ExceptionNumber** == Value)
Toast("Show message");
else
Toast("Error doing some work: " + e.toString());
}
如果您想以不同的方式处理不同的异常,请捕获它们。
try{
}catch(IOException e1){
//-- if io error--
}catch(FormatException e2){
//--if format error--
}catch(Exception e3){
//--any thing else --
}
大多数Java API异常没有特殊整数,它们有类型、消息和原因。
但是,您也可以创建自己类型的异常:
public class MyIntegerException extends Exception{
private int num;
public int getInteger(){
return num;
}
public MyIntegerException(int n, String msg){
super(msg);
this.num = n;
}
}
投掷:
throw new MyIntegerException(1024,"This is a 1024 error");
捕获:
catch(MyIntegerException e){
int num = e.getInteger();
//--do something with integer--
}
如果您知道可能出现的问题,您可以抛出自己的异常并将自定义文本添加到其中:
try{
//code to execute
//in case of an error
throw new Exception("Your message here");
}
catch (Exception e){
e.printStackTrace();
}
您还可以定义自己的异常类型,就像上面的人所说的那样,并且您可以根据发生的异常类型抛出显示不同的消息。