2

When creating such function in Eclipse

public static void writeToFile() throws FileNotFoundException {

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

I was forced to add throws FileNotFoundException to method.

Now, is my understanding correct:

  • even though I used try with resources, if there is exception inside the try block, it will not be swallowed, rather bubbled up? and that is the reason I was forced to add throws keyword?
  • try with resources is something like enclosing the code in try and finally - and omitting catch clause right? So any exception that happens inside, gets bubbled up??
  • is this behavior also same in C# using?
  • 2
    Try-with-resources is no different to other code with respect to checked exception handling: you either have a `catch` block, in which you handle the exception; or you declare that the method `throws`, and you let the caller handle the exception. – Andy Turner May 25 '16 at 20:55
  • @AndyTurner So there is no catch block with try resources? All it do just ensure closing and that's it? and that is done by using try....finally under the hoods –  May 25 '16 at 20:56
  • 1
    @user200300 If you want a `catch` block you have to _add the `catch` block_. You can have a catch block with try-with-resources, but it's not automatic. Yes, all it does is ensure proper closing. – Louis Wasserman May 25 '16 at 20:56
  • @LouisWasserman Does C# using do that in the same way? –  May 25 '16 at 20:57
  • @LouisWasserman Hence the tag –  May 25 '16 at 20:59
  • Yes, the `C#` equivalent (`using`) does not swallow exceptions either. – Blorgbeard May 25 '16 at 20:59
  • @Blorgbeard ok thanks - so they are exactly the same –  May 25 '16 at 20:59
  • Try with resources automatically close the resources opened inside it. It is the same as closing the resources in a finally block. – pahan May 25 '16 at 21:02
  • I think it is slightly different to closing in finally. I think that it ensures it will attempt to close each resource. In a finally, if there is a problem with closing the first resource, it may not proceed to the second. – timbo Oct 11 '17 at 02:52

1 Answers1

2

I do not know if you found an answer to your problem. I only came across this question recently.

Question 1.

When using the try with resources block, if the resource being used throws a checked exception (like the example above) the exception MUST be caught/ handled. The throws keyword indicates the compiler that any exception thrown will be handled by the calling method and thus does not throw any error.

Question 2.

Try with resources will behave like try finally only in case of Unchecked exceptions, for checked exceptions you are expected to handle the exception in the same method using catch or use throws it as mentioned in the response to Question 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

Question 3.

For using a resource in try-with-resources block in Java, the interface AutoCloseable must be implemented. In case of C#, IDisposeable interface is implemented by the resource. One such example is the StreamReader. The using block will close the resource automatically at the end of scope but it does nothing to handle errors. For that, you'll have to use try-catch within using block.

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;
        }
    }
}

If the exception is not caught, you will see an exception raised by the IDE with the message "An unhandled exception of type 'System.Exception' occurred" in the catch block.

In the future, if you need java equivalents in C#, this link will be helpful.

ScottSummers
  • 310
  • 1
  • 13