是否可以创建一个 returns 一个 try/catch 的方法?

Is it possible to create a method that returns a try/catch?

假设我们有很多方法想要使用 System.out.println(...) 打印一些 fx 然后我们可以创建一个像

这样的方法
public void print(String msg) {
       System.out.println(...)
}

然后我们可以这样做:print("Some message") 这样速度更快,而且每次都节省我们编写 System.out.println(...) 的时间。

现在进入案例。我正在练习 Java I/O,这需要很多 try/catch。所以我不必每次都写一个 try/catch 块,我可以做一些像

这样的事情吗?
public sometype tryCatch (String objThatCanThrowExc) {
   clause = "try {
            " + objThatCanThrowExc + "
   } catch(Exception e) { 
      print(e); 
   } "
   return clause;
}

然后做这样的事情

public void server(int port) {
    ServerSocket ss = null; 
    //Assume ss is not null, and client is a Socket
    tryCatch("client = ss.accept();");
    ...
}

通过上面的代码,我只是想表达我想做的事情。我不确定是否有什么聪明的东西可以帮助我实现这一目标。另一种可能更好的方法是如果我可以做这样的事情

public void server(int port) {
        ServerSocket ss = null;
        tryCatch() {
            client = ss.accept();
        }
        ...
}

我没有太多的编程经验,所以我知道这是一个愚蠢的问题,但谁知道,也许有一些聪明的东西

在您的示例中,您使用的“子句”是一个字符串,因此除非您尝试将其解析为代码(这很复杂),否则它不会起作用。

相反,最好在 try 部分和 catch 部分使用不同的 return 语句。如果你得到一个错误说你没有 returning 任何东西,试着在 return 语句之后放置一个虚拟的 return 语句,return 为空或零或空字符串.

您正在寻找的概念称为尝试类型。类似于java.util.Optional,可以是“存在”也可以是“空”; a Try 可以是“成功”或“失败”。它没有内置于 Java,但 Vavr 库是一个 commonly-used 实现。

如果我理解正确,你想要做的是调用多个可能抛出的 IO 函数,但不要为每个函数编写相同的“捕获”逻辑。

你是对的,你想做的是以某种方式“传递”可能会抛出到另一个为你处理捕获的方法的代码。在 Java 中,这种机制不是字符串而是 lambda 函数。

我们可以这样使用它们:

import java.io.*;

class Main {

  @FunctionalInterface
  public interface Action {
    void run() throws Exception;
  }

  private static void printExceptionAndContinue(final Action action) {
    try {
      action.run();
    } catch(Exception error) {
      System.out.println(error.toString());
    }
  }

  public static void main(String[] args) {
    printExceptionAndContinue(() -> {
      // Here goes some code that might throw!
      throw new Exception("Oh no!");
    });    
    
    printExceptionAndContinue(() -> {
      // And some more
      System.out.println("Still gets called!");
    });
  }
}

对于那些说代码“字符串”不能用 strongly-typed 编译语言键入和解释的人,我鼓励他们看看 F# quotations

如果 try-catch 需要对某个对象进行某些特定操作是。我们可以。

说。我们有一个界面

public 界面 - oneOperation

public interface oneOperation{

    public void execute() throws Exception;

    default void invoke(){
        try {
            this.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

现在接口的实现只实现 execute() 方法。

其他使用 impls 的对象可以调用 invoke() 方法以防他们不希望抛出异常

不确定这是否是您要找的..