java - 尝试使用java中的资源和异常

标签 java c#

在 Eclipse 中创建此类函数时

public static void writeToFile() throws FileNotFoundException {

    try (PrintWriter out = new PrintWriter("filename.txt")) {
        out.println("Hello world");
    }
}

我被迫将抛出 FileNotFoundException 添加到方法中。

现在,我的理解是否正确:

  • 即使我对资源使用了try,如果try block 内有异常,它不会被吞噬,而是冒泡?这就是我被迫添加 throws 关键字的原因?
  • 尝试使用资源就像将代码包含在 try 和 finally 中 - 并省略 catch 子句,对吗?所以内部发生的任何异常都会冒泡?
  • 在 C# 中使用此行为是否也相同?

最佳答案

不知道您是否找到了问题的答案。我最近才想到这个问题。

问题 1。

当使用带有资源的 try block 时,如果正在使用的资源抛出已检查的异常(如上面的示例),则必须捕获/处理该异常。 throws 关键字指示编译器抛出的任何异常都将由调用方法处理,因此不会抛出任何错误。

问题 2。

只有在出现未检查异常的情况下,Try with resources 才会像 try finally 一样,对于检查异常,您应该使用 catch 或 use throws 的相同方法来处理异常,如问题 1 的响应中所述。

//this works
public static void writeToFile() throws FileNotFoundException {
    try (PrintWriter out = new PrintWriter("filename.txt")) {
        out.println("Hello world");
    }
}

//this works
public static void writeToFile() {
    try (PrintWriter out = new PrintWriter("filename.txt")) {
        out.println("Hello world");
    }
    catch(FileNotFoundException e) {
        //handle the exception or rethrow it
    }
    finally {
        //this is optional
    }
}

//this works
public static void writeToFile() {
    try (Scanner out = new Scanner(System.in)) {
        out.println("Hello world");
    }
}

//this does not work
public static void writeToFile() {
    try (PrintWriter out = new PrintWriter("filename.txt")) {
        out.println("Hello world");
    }
}
//compiler error: Multiple markers at this line
- Unhandled exception type IOException thrown by automatic close() 
 invocation on out
- Unhandled exception type IOException

问题 3。

要在Java中的try-with-resources block 中使用资源,必须实现AutoCloseable接口(interface)。对于 C#,IDisposeable 接口(interface)由资源实现。 StreamReader 就是这样的一个例子。 using block 将在作用域结束时自动关闭资源,但它不会处理错误。为此,您必须在 using block 中使用 try-catch。

public virtual void Print()
{
    using (StreamWriter reader = new StreamWriter(@"B:\test.txt"))
    {
        try
        {
            throw new Exception("Hello Exception");
        }
        catch(Exception ex)
        {
            throw;
            //or throw ex;
        }
    }
}

如果未捕获异常,您将看到 IDE 引发异常,并在 catch block 中显示消息“发生了类型为‘System.Exception’的未处理异常”。

将来,如果您需要 C# 中的 Java 等效项,this link会有帮助的。

关于java - 尝试使用java中的资源和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37447436/

相关文章:

java - 将 RXTX 集成到 Raspberry Pi 上的 OSGi 包时 Unresolved 要求

java - 如何将值发送到另一个方法

java - Android:Eclipse 无法打开

java - Foreach 协助使用类变量?

c# - C#中的序列化和Java中的反序列化

c# - 从存储过程 "WITH RESULT SETS"读取时无法使用 CommandBehavior.KeyInfo

c# - 如何在 Windows Phone 8.1 中设置支持的方向属性

java - 如何在Java中按行号搜索文本文件?

c# - 激活器.CreateInstance : Could not load type from assembly

c# - 按 Linq 子集合中的最小值排序父集合