Handle Exception with using instead of try/catch/finally caluse - C#

Shervan360 1,481 Reputation points
2022-09-24T01:18:39.85+00:00

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();  
        }  
  
    }  
}  
C#
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,378 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 112.9K Reputation points
    2022-09-25T17:41:05.667+00:00

    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.

    1 person found this answer helpful.
    0 comments No comments

  2. Liam Oliver 1 Reputation point
    2022-09-25T17:33:20.51+00:00

    Sorry but I'm only using the try catch

    0 comments No comments