C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hello,
I'd like to implement the following code without try/catch/finally structure.
How can I handle exception in 'using' structure?
using System;
using System.IO;
internal class Program
{
static void Main(string[] args)
{
//using StreamReader File1 = new("File1.txt");
// I'd like to implement the following code without try/catch/finaly structure.
//How can I handle exception in 'using' structure?
StreamReader? File1 = null;
try
{
File1 = new("File1.txt");
}
catch (FileNotFoundException)
{
Console.WriteLine("The file cannot be found.");
}
finally
{
File1?.Dispose();
}
}
}
Maybe like this:
if( !File.Exists( "File1.txt" ) )
{
Console.WriteLine( "The file cannot be found." );
}
else
{
using StreamReader File1 = new( "File1.txt" );
// . . .
}
However the solutions that are based on FileNotFoundException are more reliable, I think.
Sorry but I'm only using the try catch