How to use throw statement in catch block with C#

4 Answers

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Method();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        static void Method()
        {
            try
            {
                int value = 1 / int.Parse("0");
            }
            catch
            {
                throw;
            }
        }
    }
}


/*
run:

Attempted to divide by zero.

*/

 



answered Mar 7, 2017 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Method();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        static void Method()
        {
            try
            {
                int value = 1 / int.Parse("0");
            }
            catch (DivideByZeroException ex)
            {
                throw ex;
            }
        }
    }
}


/*
run:

Attempted to divide by zero.

*/

 



answered Mar 7, 2017 by avibootz
edited Mar 7, 2017 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Method(null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        static void Method(string s)
        {
            if (s == null)
                throw new ArgumentNullException("s");
        }
    }
}


/*
run:

Value cannot be null.
Parameter name: s

*/

 



answered Mar 7, 2017 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Method();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        static void Method()
        {
            try
            {
                int.Parse("c#");
            }
            catch (Exception)
            {
                throw; 
            }
        }
    }
}


/*
run:

Input string was not in a correct format.

*/

 



answered Mar 7, 2017 by avibootz

Related questions

1 answer 210 views
2 answers 192 views
192 views asked Nov 22, 2020 by avibootz
3 answers 249 views
249 views asked Mar 7, 2017 by avibootz
2 answers 416 views
1 answer 152 views
1 answer 135 views
135 views asked Oct 8, 2022 by avibootz
...