java创建一个自定义异常类,并在一个方法中抛出自定义异常,在该方法的catch处理程序中捕获并重新抛出

2024-12-31 04:53:15
推荐回答(5个)
回答1:

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());
        }


    }

回答2:

首先自定义一个异常类
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());
}
}

回答3:

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!

回答4:

所以你想问什么?怎么定义这个类?

回答5:

楼上正解。很好很强大