可以创建一个返回try/catch的方法吗?

huangapple go评论91阅读模式
英文:

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

问题

假设我们有许多方法,我们希望以类似于 System.out.println(...) 的方式打印一些内容,那么我们可以创建一个方法,如下所示:

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;
    // 假设 ss 不为 null,client 是一个 Socket
    tryCatch("client = ss.accept();");
    // ...
}

通过上面的代码,我只是在尝试表达我想要做的事情。我不确定是否有智能的方法可以帮助我实现这一点。另一种甚至更好的方式是,如果我可以像这样做:

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

我没有太多的编程经验,所以我知道这是一个愚蠢的问题,但谁知道呢,也许有一些聪明的方法可以做到这一点。

英文:

Say we have a lot of methods where we want to print something fx using System.out.println(...)
then we can just create a method like

public void print(String msg) {
       System.out.println(...)
}

And then we can just do: print("Some message") which is faster and saves us for writing System.out.println(...) everytime.

So now to the case. I am practicing with Java I/O, which wants hell a lot of try/catch. So instead of having to write a try/catch block everytime, can I do something like

public sometype tryCatch (String objThatCanThrowExc) {
   clause = "try {
            " + objThatCanThrowExc + "
   } catch(Exception e) { 
      print(e); 
   } "
   return clause;
}

And then do something like this

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

With the above code I am just trying to express what I want to do. I am not sure if there is something smart available to help me achieve this. Another way that could be even better is if I could do something like this

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

I have not much programming experience, so I know this is a silly question, but who knows, maybe there is something smart

答案1

得分: 4

你要寻找的概念称为“尝试类型”(Try type)。它类似于java.util.Optional,可以是“存在”或“空”;尝试类型可以是“成功”或“失败”。它并未内置于Java,但Vavr库是常用的一种实现。

英文:

The concept that you're looking for is called a Try type. It's similar to java.util.Optional, which can be either "present" or "empty"; a Try can be either "success" or "failure". It's not built into Java, but the Vavr library is one commonly-used implementation.

答案2

得分: 4

如果我理解正确,您想要做的是调用可能会抛出异常的多个IO函数,但又不想为每个函数编写重复的“catch”逻辑。

您说得对,您想要的做法实际上是将可能引发异常的代码以某种方式“传递”到另一个处理捕获的方法中。在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(() -> {
      // 这里放置一些可能会抛出异常的代码!
      throw new Exception("Oh no!");
    });    
    
    printExceptionAndContinue(() -> {
      // 还有一些其他代码
      System.out.println("仍然会被调用!");
    });
  }
}

对于那些说在强类型编译语言中无法键入和解释“代码字符串”的人,我鼓励他们查看F#引用

英文:

If I understand it correctly, what you want to do is call multiple IO functions that might throw, but without writing the same "catch" logic for each.

You are right that what you want to do is somehow "pass" the code that might throw into another method that handles the catch for you. In Java, this mechanism is not strings but lambda functions.

We can use them like this:

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!");
    });
  }
}

For those saying that a "string" of code cannot be typed and interpreted in a strongly-typed compiled language, I would encourage them to look at F# quotations.

答案3

得分: 1

在你的示例中,“clause”你正在使用一个字符串,所以除非你尝试将它解析为代码(这很复杂),否则它不会起作用。

相反,在try部分和catch部分最好有不同的返回语句。如果你收到一个错误,指示你没有返回任何内容,试着在try/catch语句之后加上一个虚拟的return语句,返回null、零或空字符串。

英文:

In your example, the "clause" you're using is a String, so unless you try parsing it as code (which is complicated) it's not going to work.

Instead it's better to have a different return statement in the try part and in the catch part. If you get an error saying that you aren't returning anything, try putting a dummy return statement after the try/catch statements which returns null or zero or the empty string.

答案4

得分: 1

如果try-catch需要与某个特定的对象操作一起工作,是的,我们可以这样做。

假设我们有一个接口

public interface - oneOperation

public interface oneOperation{

    public void execute() throws Exception;

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

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

使用这些实现的其他对象可以在他们不想抛出异常的情况下调用invoke()方法。

不确定这是否符合您的要求。。

英文:

if the try-catch needs to work with some specific operation to an object yes. we can.

Say. we have an interface

public interface - oneOperation

public interface oneOperation{

    public void execute() throws Exception;

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

now the impls of the interface only implement execute() method.

Other Objects that uses the impls can call the invoke() method in case they want the exception to be not thrown

not sure if this is what you were looking for ..

huangapple
  • 本文由 发表于 2020年10月24日 02:17:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64505404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定