2016-05-17 6 views
1

IllegalArgumentExceptionという例外を作成したいと思います。「例外があります。すべてが偽です」というメッセージが表示されます。メッセージは表示されますか?私はこれを試してみる:私の主:例外はクラスを作成し、メッセージを表示します

public class JavaApplication1 { 

    public static void main(String[] args) { 
     try{ 

      int x=5; 

     if(x<10) 



      }catch(IllegalArgumentException e){ 
    throw new IllegalArgumentException("There is an exception.All is false"); 
     // or System.out.println(" There is an exception.All is false"); ? 




     } 

    } 

クラス:

public class IllegalArgumentException { 


    public IllegalArgumentException(String il){ 
     super(il); 
    } 
} 
+1

この例外はすでに存在しますhttps://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html、カスタムステートメントを印刷しますか? – piyushj

+0

はい私は間違っていたので私の投稿を編集します –

答えて

1

拡張クラスjava.lang.Exceptionを経由してください。たとえば、次のように

public class ServiceFaultException extends Exception { 
    private static final long serialVersionUID = 7399493976582437021L; 
    private ServiceFault serviceFault; 

    public ServiceFaultException(String message, ServiceFault serviceFault) { 
     super(message); 
     this.serviceFault = serviceFault; 
    } 

    public ServiceFault getServiceFault() { 
     return serviceFault; 
    } 

    public void setServiceFault(ServiceFault serviceFault) { 
     this.serviceFault = serviceFault; 
    } 
} 

あなたは以下のようにそれを使用することができServiceFaultExceptionを使用したい:

ServiceFault sf = new ServiceFault("Error Code here", "Error Definition here", "Error Details here"); 
throw new ServiceFaultException("Error Name", sf); 

そして、あなたがキーワードをスローするか、この例外をキャッチし、などのコンソールに書くことができるとの例外をスローすることができますあなたの例外クラスは、私はギブきた例よりも基本になります。

UPDATE

n。以下に、あなたの例外クラスです:

import java.lang.Exception; 

// Don't forget to serialize your custom exception class (this class). 
public class SomethingException extends Exception{ 
    public SomethingException(String il){ 
     super(il); 
    } 
} 

メインクラスは、このようなものでなければなりません:あなたはより具体的なデータが含まれているPOJOクラスを使用して例外クラスを向上させることができることを忘れないでください

import com.somewhere.SomethingException; 
    public class JavaApplication1 { 
       public static void main(String[] args) { 
        try{ 
         int x=5; 
         // if(x<10){} // you don't need this line. 
         x = x/0; // The condition to jump into catch scope. 
        }catch(ArithmeticException e){ // You can define your own exception here. 
         throw new SomethingException("There is an exception.All is false"); 
        } 
       } 
      } 

あなたの必要に応じて。私の最初の例では、ServiceFaultはscreenCodeやソースなどの属性を持つクラスです

+0

私はあなたがそれを再度見ることができるpost.Ifをedditedしています私はそれを感謝します –

+0

私は違いを気付くことはできません。どの部分を編集しましたか? –

+0

申し訳ありませんが、私のメインでは何かが間違っていて、それは動作しませんか、あなたの答えで私はメッセージを置くべきであることを理解しています "exception.Allは偽です" –

1

このクラスはすでに実装チェックあなたがあなた自身のEXCを作成することができ、このlink

関連する問題