Java:如何在for-loop中将try-catch作为条件?

hhh*_*hhh 0 java conditional for-loop

我知道如何通过将大小与上限进行比较来解决问题,但我想要一个查找异常的条件.如果在conditinal中发生异常,我想退出.

import java.io.*;
import java.util.*;

public class conditionalTest{
        public static void main(String[] args){

                Stack<Integer> numbs=new Stack<Integer>();
                numbs.push(1);
                numbs.push(2);
                for(int count=0,j=0;try{((j=numbs.pop())<999)}catch(Exception e){break;}&&
                                !numbs.isEmpty(); ){
                                System.out.println(j);
                }
                // I waited for 1 to be printed, not 2.

        }
}
Run Code Online (Sandbox Code Playgroud)

一些错误

javac conditionalTest.java
conditionalTest.java:10: illegal start of expression
            for(int count=0,j=0;try{((j=numbs.pop())<999)}catch(Exception e){break;}&&
                                ^
conditionalTest.java:10: illegal start of expression
            for(int count=0,j=0;try{((j=numbs.pop())<999)}catch(Exception e){break;}&&
                                   ^
Run Code Online (Sandbox Code Playgroud)

pol*_*nts 6

您不应该使用Exception正常的控制流,也不能将语句用作循环终止条件,它需要是一个boolean 表达式.

在这种特殊情况下,它看起来像你可以使用!numbs.isEmpty() && (j=numbs.pop()) < 999.这是有效的,因为它&&是短路的,如果是左手false,它将不会评估右手(它会抛出一个Exception),因为没有必要:false尽管如此,整体表达仍然如此.

在这样&&的结构中也利用了这种短路:

if (s != null && s.startsWith("prefix")) { ...
Run Code Online (Sandbox Code Playgroud)