Csharp/C Sharp/Language Basics/Exception Throw

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Demonstrates rethrowing an exception from a method

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//  Rethrow.cs -- Demonstrates rethrowing an exception from a method.
//
//                Compile this program with the following command line:
//                    C:>csc Rethrow.cs
//
namespace nsRethrow
{
    using System;
    using System.IO;
    
    public class Rethrow
    {
        static public void Main ()
        {
            while (true)
            {
                Console.Write ("Please enter a file name (return to exit): ");
                string FileName = Console.ReadLine ();
                if (FileName.Length == 0)
                    break;
                try
                {
                    ReadFile (FileName);
                    break;
                }
                catch (IOException e)
                {
                    if (e is FileNotFoundException)
                        Console.WriteLine ("The file " + FileName + " was not found");
                }
                catch (Exception e)
                {
                    Console.WriteLine (e.Message + "\n");
                    break;
                }
            }
        }
        static public void ReadFile (string FileName)
        {
            FileStream strm;
            StreamReader reader;
            try
            {
                strm = new FileStream (FileName, FileMode.Open);
                reader = new StreamReader (strm);
                string str = reader.ReadToEnd ();
                Console.WriteLine (str);
            }
            catch (IOException e)
            {
                // If file not found, go back and get another name
                if (e is FileNotFoundException)
                    throw (e);
                // Code here to handle other IOException classes
                Console.WriteLine (e.Message);
                throw (new IOException());
            }
        }
    }
}


Exception throw and catch

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 namespace ExceptionHandling
 {
    public class TesterExceptionHandling2
    {
       static void Main()
       {
           Console.WriteLine("Enter Main...");
           TesterExceptionHandling2 t = new TesterExceptionHandling2();
           t.Run();
           Console.WriteLine("Exit Main...");
       }
       public void Run()
       {
           Console.WriteLine("Enter Run...");
           Func1();
           Console.WriteLine("Exit Run...");
       }

        public void Func1()
        {
            Console.WriteLine("Enter Func1...");
            Func2();
            Console.WriteLine("Exit Func1...");
        }
        public void Func2()
        {
            Console.WriteLine("Enter Func2...");
            try
            {
                Console.WriteLine("Entering try block...");
                throw new System.Exception();
                Console.WriteLine("Exiting try block...");
            }
            catch
            {
                Console.WriteLine("Exception caught and handled!");
            }
            Console.WriteLine("Exit Func2...");
        }
    }
 }


Exception throw and catch 2

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 namespace ExceptionHandling
 {
    public class TesterExceptionHandling3
    {
       static void Main()
       {
           Console.WriteLine("Enter Main...");
           TesterExceptionHandling3 t = new TesterExceptionHandling3();
           t.Run();
           Console.WriteLine("Exit Main...");
       }
       public void Run()
       {
           Console.WriteLine("Enter Run...");
           Func1();
           Console.WriteLine("Exit Run...");
       }

        public void Func1()
        {
            Console.WriteLine("Enter Func1...");
            try
            {
                Console.WriteLine("Entering try block...");
                Func2();
                Console.WriteLine("Exiting try block...");
            }
            catch
            {
                Console.WriteLine("Exception caught and handled!");
            }
            Console.WriteLine("Exit Func1...");
        }
        public void Func2()
        {
            Console.WriteLine("Enter Func2...");
            throw new System.Exception();
            Console.WriteLine("Exit Func2...");
        }
    }
 }


Exception throws

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 namespace ExceptionHandling
 {
    public class TesterExceptionHandling1
    {
       static void Main()
       {
           Console.WriteLine("Enter Main...");
           TesterExceptionHandling1 t = new TesterExceptionHandling1();
           t.Run();
           Console.WriteLine("Exit Main...");
       }
       public void Run()
       {
           Console.WriteLine("Enter Run...");
           Func1();
           Console.WriteLine("Exit Run...");
       }
        public void Func1()
        {
            Console.WriteLine("Enter Func1...");
            Func2();
            Console.WriteLine("Exit Func1...");
        }
        public void Func2()
        {
            Console.WriteLine("Enter Func2...");
            throw new System.Exception();
            Console.WriteLine("Exit Func2...");
        }
    }
 }


illustrates creating and throwing an exception object

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example13_8.cs illustrates creating and
  throwing an exception object
*/
using System;
public class Example13_8
{
  public static void Main()
  {
    try
    {
      // create a new Exception object, passing a string
      // for the Message property to the constructor
      Exception myException = new Exception("myException");
      // set the HelpLink and Source properties
      myException.HelpLink = "See the Readme.txt file";
      myException.Source = "My Example13_8 Program";
      // throw the Exception object
      throw myException;
    }
    catch (Exception e)
    {
      // display the exception object"s properties
      Console.WriteLine("HelpLink = " + e.HelpLink);
      Console.WriteLine("Message = " + e.Message);
      Console.WriteLine("Source = " + e.Source);
      Console.WriteLine("StackTrace = " + e.StackTrace);
      Console.WriteLine("TargetSite = " + e.TargetSite);
    }
  }
}


Intentionally throws an error to demonstrate Just-In-Time debugging

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//  Throw.cs -- Intentionally throws an error to demonstrate
//              Just-In-Time debugging.
//
//              Compile this program with the following command line:
//                  C:>csc /debug:full Throw.cs
//
namespace nsThrow
{
    using System;
    
    public class Throw
    {
        static public void Main ()
        {
            Console.WriteLine ("This program intentionally causes an error.");
            int x = 42;
            int y = 0;
            int z = x / y;
        }
    }
}


Let the C# runtime system handle the error

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Let the C# runtime system handle the error. 
 
using System; 
 
public class NotHandled { 
  public static void Main() { 
    int[] nums = new int[4]; 
 
    Console.WriteLine("Before exception is generated."); 
 
    // Generate an index out-of-bounds exception. 
    for(int i=0; i < 10; i++) { 
      nums[i] = i; 
      Console.WriteLine("nums[{0}]: {1}", i, nums[i]); 
    } 
 
  } 
}


Manually throw an exception

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Manually throw an exception. 
 
using System; 
 
public class ThrowDemo { 
  public static void Main() { 
    try { 
      Console.WriteLine("Before throw."); 
      throw new DivideByZeroException(); 
    } 
    catch (DivideByZeroException) { 
      // catch the exception 
      Console.WriteLine("Exception caught."); 
    } 
    Console.WriteLine("After try/catch block."); 
  } 
}


Rethrow an exception

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Rethrow an exception. 
 
using System; 
 
class Rethrow { 
  public static void genException() { 
    // here, numer is longer than denom 
    int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 }; 
    int[] denom = { 2, 0, 4, 4, 0, 8 }; 
 
    for(int i=0; i<numer.Length; i++) { 
      try { 
        Console.WriteLine(numer[i] + " / " + 
                          denom[i] + " is " + 
                          numer[i]/denom[i]); 
      } 
      catch (DivideByZeroException) { 
        // catch the exception 
        Console.WriteLine("Can"t divide by Zero!"); 
      } 
      catch (IndexOutOfRangeException) { 
        // catch the exception 
        Console.WriteLine("No matching element found."); 
        throw; // rethrow the exception 
      } 
    } 
  }   
} 
 
public class RethrowDemo { 
  public static void Main() { 
    try { 
      Rethrow.genException(); 
    } 
    catch(IndexOutOfRangeException) { 
      // recatch exception 
     Console.WriteLine("Fatal error -- " + 
                       "program terminated."); 
    } 
  } 
}


Throwing Your Own Exceptions

 

using System;
   
class MyException : ApplicationException
{
    public MyException() : base("This is my exception message.")
    {
    }
}
   
class MainClass
{
    public static void Main()
    {
        try
        {
            MainClass MyObject = new MainClass();
   
            MyObject.ThrowException();
        }
        catch(MyException CaughtException)
        {
            Console.WriteLine(CaughtException.Message);
        }
    }
   
    public void ThrowException()
    {
        throw new MyException();
    }
}