public void MyException(String name){
if(null==name || "".equals(name)){
throw new RuntimeException("姓名的格式不正确");
}
}
public static void main(String[] args) {
try {
new aaa().MyException("");
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
}
首先自定义一个异常类
public class ActionException extends Exception{
public String returnMessage;
public ActionException(String returnMessage){
this.returnMessage = returnMessage;
}
public String getReturnMessage(){
return this.returnMessage;
}
代码中如果用到这个自定义的异常类,这里的代码只是做了个演示
private void validate(int a,int b)throws ActionException{
if(a>b){
throw new ActionException("a > b");
}
if(a throw new ActionException("a < b");
}
}
业务逻辑代码中
public String process(){
try{
validate(a,b);
}catch(ActionException ae){
System.out.println(ae.getReturnMessage());
}
}
public class sssss {
public static void main(String[] args) {
System.out.print("Please input an Integer: ");
int value = new Scanner(System.in).nextInt();
try{
if(value < 0){
throw new MyException("My Exception comes!");
}
}catch (MyException myExp){
System.out.println("MyExcepton caugth!");
}
}
}
class MyException extends Exception{
public MyException(String s){
System.out.println("MyException occurs. The value must be greater than ZERO!");
}
}
-----------------------
Please input an Integer: -5
MyException occurs. The value must be greater than ZERO!
MyExcepton caugth!
所以你想问什么?怎么定义这个类?
楼上正解。很好很强大