gpt4 book ai didi

Java:IOException 的危险自返回递归函数?

转载 作者:行者123 更新时间:2023-11-29 06:22:10 24 4
gpt4 key购买 nike

我在使用 if 子句时遇到了非常错误的异常处理。如果找不到路径,则会发生异常。异常再次返回该函数。该函数是递归的。安全吗?

$ javac SubDirs.java $ java SubDirsGive me an path..Dir1Dir2Give me an path.IT WON'T FIND ME, SO IT RETURNS ITSELF due to Exception caughtGive me an path.

The code of Subdirs.java looks like this:

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

public class SubDirs {
private List<File> getSubdirs(File file) throws IOException {
List<File> subdirs = Arrays.asList(file.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory();
}
}));
subdirs = new ArrayList<File>(subdirs);

List<File> deepSubdirs = new ArrayList<File>();
for(File subdir : subdirs) {
deepSubdirs.addAll(getSubdirs(subdir));
}
subdirs.addAll(deepSubdirs);
return subdirs;
}

public static void search() {
try{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
System.out.println("Give me an path.");
while ((s = in.readLine()) != null && s.length() != 0){
SubDirs dirs = new SubDirs();
List<File> subDirs = dirs.getSubdirs(new File(s));
for ( File f : subDirs ) {
System.out.println(f.getName());
}
System.out.println("Give me an path.");
}
}catch(Exception e){
// Simple but is it safe?
search();
}
}

public static void main(String[] args) throws IOException {
search();
}
}

最佳答案

是的,在您输入错误路径数千次之前,它是安全的。

关于Java:IOException 的危险自返回递归函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2623432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com