0

何が起こったのかをよりよく制御するために例外番号を取得する方法はありますか?

例えば:

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

2 に答える 2

2

異なる方法で処理したい場合は、異なる例外をキャッチします。

try{

}catch(IOException e1){
  //-- if io error--
}catch(FormatException e2){
  //--if format error--
}catch(Exception e3){
  //--any thing else --
}

ほとんどのJavaAPI例外には特別な整数がなく、タイプ、メッセージ、および原因があります。

ただし、独自のタイプの例外を作成することもできます。

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--
}
于 2013-02-09T09:16:02.217 に答える
0

何がうまくいかないかわかっている場合は、独自の例外をスローして、カスタム テキストを追加できます。

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

上記の人が言ったように、独自の例外タイプを定義することもでき、発生した例外タイプに応じて異なるメッセージを表示できます。

于 2013-02-09T09:24:37.880 に答える