Reputation: 197
I want to create an exception named IllegalArgumentException.I should appear a message to "There is an exception.All is false".Where should i appear a message?How can i do this ?I have try this: My main :
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"); ?
}
}
the class :
public class IllegalArgumentException {
public IllegalArgumentException(String il){
super(il);
}
}
Upvotes: 1
Views: 65
Reputation: 570
You can create your own exception class via extending java.lang.Exception
. For example :
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;
}
}
When you want to use the ServiceFaultException you can use it like below:
ServiceFault sf = new ServiceFault("Error Code here", "Error Definition here", "Error Details here");
throw new ServiceFaultException("Error Name", sf);
And you can throw exception with throws keyword or you can catch this exception and write to console etc.
UPDATE
Your Exception class will be more basic than the example i've given. Below, is your Exception class:
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);
}
}
The main class should be something like this :
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");
}
}
}
Don't forget that you can improve your Exception class with a POJO class that contains more specific data according to your needs. In my first Example ServiceFault is the class that has attributes like screenCode, source etc.
Upvotes: 1