简体   繁体   English

尝试使用if语句捕获块

[英]Try catch block with an if statement

So I got some problems implementing a try catch block in my program. 所以我在程序中实现try catch块时遇到了一些问题。 It's quite simple, all I want is to throw an exception whenever the user enters a 0 or less into my dialog window. 这很简单,只要用户在我的对话框窗口中输入0或更少,我只想抛出一个异常。 Here is my code: 这是我的代码:

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

The NegativeSidesException is my own defined exception. NegativeSidesException是我自己定义的异常。

When I make 0 the input the try catch block doesn't catch it and the compiler throws a normal exception and terminates the program. 当我将输入设为0时,try catch块将无法捕获它,并且编译器将引发正常异常并终止程序。

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

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

And every thing will work as you want 每件事都可以随心所欲

Create a new object for the exception and throw it explicitly. 为该异常创建一个新对象,并明确地抛出它。

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

You have so bad syntax :) 你的语法太糟糕了:)

1) if statement as it is doesn't throw exception of it's own 1) if语句本身不会抛出异常

Lets repeat :) 让我们重复一遍:)

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;

Try-Catch: 试着抓:

try{
 //danger code
}catch(ExceptionClass e){
 //work with exception 'e'
}

2) There are more ways how to make that : 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");
}

Or maybe better: 也许更好:

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

Btw You can use java default Exception (that message is better to specify as constant in above of class): 顺便说一句,您可以使用java默认的Exception (最好在类的上面将该消息指定为常量):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM