How to use try catch throw in C#

2 Answers

0 votes
using System;
  
class Program
{
    static void test(string s) {
        if (s == null) {
            throw new ArgumentNullException();
        }
    }
  
    static void Main()
    {
        string s = null; 
  
        try { 
            test(s);
        }
        catch (Exception ex) {
            Console.WriteLine("catch (Exception ex): {0}", ex);
        }
    }
}
  
  
  
  
/*
run:
  
catch (Exception ex): System.ArgumentNullException: Value cannot be null.
  at Program.Main () [0x00002] in <06380fb13dc741b4b4b44fee5649d698>:0 
  
*/

 



answered Nov 22, 2020 by avibootz
edited Nov 23, 2020 by avibootz
0 votes
using System;
 
class Program
{
    static void test(string s) {
        if (s == null) {
            throw new ArgumentNullException();
        }
    }
 
    static void Main()
    {
        try {
            string s = null;
            test(s);
        }
        catch (ArgumentNullException ex) {
            Console.WriteLine("catch (ArgumentNullException ex): {0}", ex);
        }
        catch (Exception ex) {
            Console.WriteLine("catch (Exception ex): {0}", ex);
        }
    }
}
 
 
 
 
/*
run:
 
catch (ArgumentNullException ex): System.ArgumentNullException: Value cannot be null.
  at Program.Main () [0x00002] in <d1d2cd0e27104097b286d3b2e5edcf4a>:0 
 
*/

 



answered Nov 23, 2020 by avibootz
edited Nov 23, 2020 by avibootz

Related questions

1 answer 134 views
134 views asked Oct 8, 2022 by avibootz
2 answers 285 views
3 answers 305 views
305 views asked Jan 3, 2016 by avibootz
1 answer 240 views
4 answers 333 views
1 answer 219 views
219 views asked Nov 23, 2020 by avibootz
...