Home > Backend Development > C#.Net Tutorial > [C# Tutorial] C# Exception Handling

[C# Tutorial] C# Exception Handling

黄舟
Release: 2016-12-24 13:35:15
Original
1239 people have browsed it

C# Exception Handling

Exceptions are problems that occur during program execution. An exception in C# is a response to a special situation that occurs while the program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control of a program from one part to another. C# exception handling is based on four keywords: try, catch, finally and throw.

try: A try block identifies a block of code that will trigger a specific exception. Followed by one or more catch blocks.

catch: The program catches exceptions through exception handlers. The catch keyword indicates exception catching.

finally: The finally block is used to execute a given statement regardless of whether an exception is thrown. For example, if you open a file, the file will be closed regardless of whether an exception occurs.

throw: When a problem occurs, the program throws an exception. Use the throw keyword to accomplish this.

Syntax

Suppose a block will throw an exception and a method catches the exception using try and catch keywords. The code inside the try/catch block is protected code. Use the try/catch syntax as follows:

try
{
   // 引起异常的语句
}
catch( ExceptionName e1 )
{
   // 错误处理代码
}
catch( ExceptionName e2 )
{
   // 错误处理代码
}
catch( ExceptionName eN )
{
   // 错误处理代码
}
finally
{
   // 要执行的语句
}
Copy after login

You can list multiple catch statements to capture different types of exceptions to prevent the try block from generating multiple exceptions under different circumstances. An exception.

Exception classes in C#

C# exceptions are represented by classes. The exception classes in C# are mainly derived directly or indirectly from the System.Exception class. The System.ApplicationException and System.SystemException classes are exception classes derived from the System.Exception class.

The System.ApplicationException class supports exceptions generated by applications. Therefore, all exceptions defined by the programmer should be derived from this class.

The System.SystemException class is the base class for all predefined system exceptions.

The following table lists some predefined exception classes derived from the Sytem.SystemException class:

Exception Class

Description

System.IO.IOException Handles I/O errors.

System.IndexOutOfRangeException Handles the error generated when a method points to an array index that is out of range.

System.ArrayTypeMismatchException Handles errors generated when array types do not match.

System.NullReferenceException Handles errors generated when relying on a null object.

System.DivideByZeroException Handles errors generated when dividing by zero.

System.InvalidCastException Handles errors generated during type conversion.

System.OutOfMemoryException Handles errors generated by insufficient free memory.

System.StackOverflowException Handles errors generated by stack overflow.

Exception handling

C# provides a structured exception handling solution in the form of try and catch blocks. Use these blocks to separate core program statements from error handling statements.

These error handling blocks are implemented using try, catch and finally keywords. Here is an example of an exception being thrown when dividing by zero:

using System;
namespace ErrorHandlingApplication
{
    class DivNumbers
    {
        int result;
        DivNumbers()
        {
            result = 0;
        }
        public void division(int num1, int num2)
        {
            try
            {
                result = num1 / num2;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Exception caught: {0}", e);
            }
            finally
            {
                Console.WriteLine("Result: {0}", result);
            }

        }
        static void Main(string[] args)
        {
            DivNumbers d = new DivNumbers();
            d.division(25, 0);
            Console.ReadKey();
        }
    }
}
Copy after login

When the above code is compiled and executed, it produces the following results:

Exception caught: System.DivideByZeroException: Attempted to divide by zero. 
at ...
Result: 0
Copy after login

Creating user-defined exceptions

You can also define your own exceptions . User-defined exception classes are derived from the ApplicationException class. The following example demonstrates this:

using System;
namespace UserDefinedException
{
   class TestTemperature
   {
      static void Main(string[] args)
      {
         Temperature temp = new Temperature();
         try
         {
            temp.showTemp();
         }
         catch(TempIsZeroException e)
         {
            Console.WriteLine("TempIsZeroException: {0}", e.Message);
         }
         Console.ReadKey();
      }
   }
}
public class TempIsZeroException: ApplicationException
{
   public TempIsZeroException(string message): base(message)
   {
   }
}
public class Temperature
{
   int temperature = 0;
   public void showTemp()
   {
      if(temperature == 0)
      {
         throw (new TempIsZeroException("Zero Temperature found"));
      }
      else
      {
         Console.WriteLine("Temperature: {0}", temperature);
      }
   }
}
Copy after login

When the above code is compiled and executed, it produces the following results:

TempIsZeroException: Zero Temperature found
Copy after login

Throwing object

If the exception is directly or indirectly derived from the System.Exception class, you can Throws an object. You can throw the current object using a throw statement inside a catch block like this:

Catch(Exception e)
{
   ...
   Throw e
}
Copy after login

 以上就是【c#教程】C# 异常处理的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template