gpt4 book ai didi

Java 说我必须返回一个对象,但我抛出异常

转载 作者:行者123 更新时间:2023-11-29 07:46:57 27 4
gpt4 key购买 nike

所以我试图捕获无法返回目录的异常,但 Java 不允许。我如何构建代码以便 Java 让我运行它?

public Directory pathToDir(String path) throws Exception {
String[] arrayPath = path.split("/");
Directory cwd_copy = FileSystem.getRoot();
try {
// full path
if (path.startsWith("/")) {
for (int x = 1; x < arrayPath.length; x++) {
if (stuff) {
} else {
throw new Exception();
}
}
}
return cwd_copy;
}
catch (Exception e) {
pathErrorMsg();
}
}

最佳答案

不,您可能抛出一个异常,但随后您捕获了它却什么都不做!如果您从逻辑上单步执行该代码,您会发现该方法有可能在不返回 Directory 且不抛出异常的情况下结束。那不会飞。

相反,请考虑......

public Directory pathToDir(String path) throws PathToDirException {
String[] arrayPath = path.split("/");
Directory cwd_copy = FileSystem.getRoot();
// full path
if (path.startsWith("/")) {
for (int x = 1; x < arrayPath.length; x++) {
if (stuff) {
} else {
throw new PathToDirException( /* some text goes in here! */ );
}
}
}
return cwd_copy;
}

其中 PathToDirException 是您为该方法/类的问题创建的检查异常类。

或者如果您在方法中有一个 try/catch block ,然后需要抛出一个异常,抛出您的新异常类,但将捕获的异常作为构造函数参数传递给您的新异常。

关于Java 说我必须返回一个对象,但我抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24947229/

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