How to use the Try/Catch block to catch exceptions in C#

2 Answers

0 votes
using System;
using System.IO;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                StreamReader sr = File.OpenText("c:\\data.txt");
                Console.WriteLine("The first text: {0}", sr.ReadLine());
                sr.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} - {1}", e.GetType(), e.Message);
            }
        }
    }
}


/*
run:
 
System.IO.FileNotFoundException - Could not find file 'c:\data.txt'.
 
*/

 



answered Apr 9, 2016 by avibootz
0 votes
using System;
using System.IO;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                StreamReader sr = File.OpenText("c:\\data.txt");
                Console.WriteLine("The first text:  {0}", sr.ReadLine());
                sr.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}


/*
run:
 
System.IO.FileNotFoundException: Could not find file 'c:\data.txt'.
File name: 'c:\data.txt'
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, I
nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions o
ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolea
n useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access,
FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean
bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detec
tEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path)
   at System.IO.File.OpenText(String path)
   at ConsoleApplication_C_Sharp.Program.Main(String[] args) in D:\directx\Conso
leApplication_C_Sharp\ConsoleApplication_C_Sharp\Program.cs:line 12
 
*/

 



answered Apr 9, 2016 by avibootz

Related questions

2 answers 359 views
2 answers 295 views
1 answer 212 views
1 answer 193 views
193 views asked Dec 17, 2016 by avibootz
1 answer 209 views
1 answer 247 views
1 answer 213 views
...