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.