尝试使用if语句捕获块

Bax*_*tex 0 java try-catch

所以我在程序中实现try catch块时遇到了一些问题.这很简单,我想要的只是当用户在对话框窗口输入0或更少时抛出异常.这是我的代码:

try {
    if (this.sides <= 0);
} catch (NegativeSidesException exception) {
    System.out.println(exception + "You entered 0 or less");
}
Run Code Online (Sandbox Code Playgroud)

NegativeSidesException是我自己定义的异常.

当我输入0时,try catch块没有捕获它,编译器抛出一个正常的异常并终止程序

小智 7

更改 if (this.sides <= 0);

if (this.sides <= 0) throw new Exception ("some error message");

每件事都会按你的意愿行事


Kus*_*ush 6

为异常创建一个新对象并显式抛出它.

try{
    if (this.sides <= 0)
        throw new NegativeSidesException();
}
catch (NegativeSidesException exception)
{
    System.out.println(exception + "You entered 0 or less");        
}
Run Code Online (Sandbox Code Playgroud)


xxx*_*xxx 5

你的语法太糟糕了:)

1)if语句本身不会抛出异常

让我们重复一遍:)

如果:

if(condition){
 //commands while true
}

if(condition)
 //if there is just 1 command, you dont need brackets

if(condition){
 //cmd if true
}else{
 //cmd for false
}

 //theoretically (without brackets)
    if(condition)
     //true command;
    else
     //false command;
Run Code Online (Sandbox Code Playgroud)

试着抓:

try{
 //danger code
}catch(ExceptionClass e){
 //work with exception 'e'
}
Run Code Online (Sandbox Code Playgroud)

2)有更多的方法来做到这一点:

try{
    if (this.sides <= 0){
          throw new NegativeSidesException();
    }else{
           //make code which you want- entered value is above zero
           //in fact, you dont need else there- once exception is thrown, it goes into catch automatically
    }
}catch(NegativeSidesException  e){
   System.out.println(e + "You entered 0 or less");
}
Run Code Online (Sandbox Code Playgroud)

或者也许更好:

try{
    if (this.sides > 0){
         //do what you want
    }else{
           throw new NegativeSidesException();
    }
 }catch(NegativeSidesException  e){
    System.out.println(e + "You entered 0 or less");
 }
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您可以使用 java 默认异常(该消息最好在类的上面指定为常量):

throw new Exception("You entered 0 or less); 
//in catch block
System.out.println(e.getMessage());
Run Code Online (Sandbox Code Playgroud)