public WHATTOWRITEHERE test()
{
try
{
transaction.begin();
code which may trigger exception
transaction.commit();
return true;
}
catch (javax.script.ScriptException ex)
{
transaction.rollback();
return ex.getMessage();
}
}
上面的代码打算做某事,如果成功则返回true
,如果不成功(发生错误),则应返回此错误消息string
。 Php 可以,但 Java 不行
编辑:期望不能传到外面,它必须在这里处理。
最佳答案
您不能返回多种类型,但您可以重新设计,这样就不必这样做。一些可能性:
- 不要返回错误消息。相反,抛出或重新抛出异常并让调用者处理它。
- 创建一些可以封装成功和错误状态以及所有相关信息的类,并返回该类的实例。
我推荐选项 1。您已经在处理异常,您可以看到它在错误处理中的用途。没有理由阻止它在那里,处理任何本地清理,然后将其交给调用者。
<小时/>现在我回到键盘上,一些仓促构建的示例仅用于说明概念,并非详尽无遗或必须逐字使用:
清理然后重新抛出:
public boolean test () throws javax.script.ScriptException {
try {
transaction.begin();
...
transaction.commit();
return true;
} catch (javax.script.ScriptException ex) {
transaction.rollback();
throw ex;
}
}
清理然后根据需要重新抛出不同的异常类型:
public boolean test () throws MyGreatException {
try {
transaction.begin();
...
transaction.commit();
return true;
} catch (javax.script.ScriptException ex) {
transaction.rollback();
throw new MyGreatException(ex);
}
}
返回一个提供状态信息的对象(这只是一般思想的一个简单示例):
public class TransactionResult {
private final boolean failed;
private final String reason;
/** Construct a result that represents a successful transaction. */
public TransactionResult () {
failed = false;
reason = null;
}
/** Construct a result that represents a failed transaction with a reason. */
public TransactionResult (String failedReason) {
failed = true;
reason = failedReason;
}
public boolean isFailed () {
return failed;
}
public String getReason () {
return reason;
}
}
然后:
public TransactionResult test () {
TransactionResult result;
try {
transaction.begin();
...
transaction.commit();
result = new TransactionResult();
} catch (javax.script.ScriptException ex) {
transaction.rollback();
result = new TransactionResult(ex.getMessage());
}
return result;
}
等等
关于Java,如果我想从函数返回不同类型怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39182100/