2013-02-09 31 views
0

有没有办法让异常号码更好地控制发生了什么?例外号码和字符串

例如:

try 
    { Do some work 
    } 
    catch(Exception e) 
    { if(e.**ExceptionNumber** == Value) 
      Toast("Show message"); 
     else 
      Toast("Error doing some work: " + e.toString());   
    } 
+0

你想达到什么目的? – Sean 2013-02-09 09:10:02

回答

2

捕获不同的例外,如果你想以不同的方式处理它们。

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-- 
} 
+0

我只需要“catch(Exception e3)”。我想登录一个erros数据库。我需要一个整数的异常而不是一个字符串。 – Ton 2013-02-09 09:26:18

+0

@Ton Java的例外不会存储错误的特殊数字。在答案中更新。 – 2013-02-09 09:36:11

+0

好的。谢谢。我想没有解决办法。如果没有错误代码作为整数,我想我必须比较字符串。 – Ton 2013-02-09 12:45:22

0

,如果你知道什么可以去错了,你可以抛出你自己的例外,并添加自定义文本:

try{ 
    //code to execute 
    //in case of an error 
    throw new Exception("Your message here"); 
} 
catch (Exception e){ 
e.printStackTrace(); 
} 

您也可以定义自己的异常类型,就像上面说的人一样,您可以根据发生的异常类型显示不同的消息。