search
HomeBackend DevelopmentC#.Net TutorialC# basic knowledge compilation: basic knowledge (13) exception

Often when we write code, we always encounter certain problems during operation that cause the program to crash. This is not because the programmer's level is not good, but because of problems with the business logic, operating system, or other equipment such as computers. For example, some methods in user32.dll are often used in C#. If this file is deleted , your program still cannot run. Of course, as a skilled programmer, you always need to take various situations into consideration when writing a program. The higher the level, the more situations you have to consider, and the more you consider, the less chance your program will crash. The better the robustness.
Generally speaking, there are two situations when the program cannot run:
One is an error. It includes environment errors (such as missing files, incorrect file content, resulting in inconsistency with the program agreement, unsupported system versions, etc.); memory operation errors (such as insufficient memory leading to failure to allocate memory); program logic errors (this is generally Process errors lead to wrong results in the program, etc.);
The second is exceptions. An exception means that the program cannot run due to factors in the current process or unexpected behavior. Generally include:
Illegal operations, the user inputs wrong instructions; abnormal input and output, non-hardware problems when accessing external devices, such as when reading and writing hard disks, the result is that external virtual optical drives, floppy disks, etc. are also used as hard disks, or There is no problem with the program itself, but errors are still reported when reading and writing from the hard disk; memory allocation is abnormal and when memory is insufficient, new objects cannot be created.
Generally speaking, there is a key difference between errors and exceptions. Errors are not allowed to occur. Once they occur, the program must be modified and the operating environment must be changed; exceptions are part of the program, no matter what program is more or less All types of exceptions will be encountered. When exceptions occur, the program must handle exceptions, but exceptions should not affect the continued operation of the program. For errors, correct them when they occur. Let’s take a look at exception handling in C#.
Generally speaking, in order to ensure that the program does not make mistakes, a lot of if...else judgments will be made. However, a wise man will make mistakes after careful consideration. Even a master cannot make the program comprehensive and think of all situations. So this is the way we should use exception handling in C#. C# uses a catch-and-throw model to handle exceptions. When an exception occurs in the program, the exception object is captured at the place where the exception is handled. What is thrown is an object of the Exception class or its subclass, such as:
ArgumentException: This exception is thrown when the parameter is illegal.
ArgumentNullException: This exception is thrown when the parameter is null.
ArgumentOutOfRangeException: This exception is thrown when the parameter exceeds the allowed range.
The format for capturing exceptions is as follows:

            try
            {
                //代码段
            }
            catch (Exception ex)
            {
                //处理异常
            }
            finally
            {
                //最后一定执行的
            }

The try code block contains code that may cause exceptions. You can use the throw keyword to throw exceptions, or you can access any properties or methods that may throw exceptions;
catch code block is used to capture the exception to be caught and contains the code to handle the exception;
finally code block represents the code segment that is executed after the exception handling is completed, that is, the code segment in finally is always executed last, and No matter whether the exception is caught or not.
Look at the following pieces of code:
Inherited from Exception and intuitively understand the Exeption class:

  public class MySelfException : Exception
    {
        /// <summary>
        /// 默认构造器
        /// </summary>
        public MySelfException()

            : base()
        {

        }
        /// <summary>
        /// 提供一个string类型的参数构造器,可设置自定义信息
        /// </summary>
        /// <param name="message"></param>
        public MySelfException(string message)

            : base(message)
        {

        }

        /// <summary>
        /// 用于传入异常信息,另外可以传入该异常有哪个其它异常引发的
        /// </summary>
        /// <param name="message"></param>
        /// <param name="innerException"></param>
        public MySelfException(string message, Exception innerException)

            : base(message, innerException)
        {

        }
        /// <summary>
        /// 覆盖Message属性,返回经过处理的异常信息
        /// </summary>
        public override string Message
        {
            get
            {
                return "有异常:" + base.Message;
            }
        }
    }

Look at the process of catching and throwing:

  public class Exceptions
    {
        public static void PersonInfo(string name, char sex, int age)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            if (sex != &#39;男&#39; && sex != &#39;女&#39;)
            {
                throw new ArgumentException("sex只能为“男”或“女”");
            }

            if (age <= 0 || age >= 150)
            {
                throw new ArgumentOutOfRangeException("age");
            }

            Console.WriteLine(string.Format(@"name={0},sex={1},age={2}", name, sex, age));
        }

        public static void Throwable(bool canThrow, int num)
        {
            if (canThrow)
            {
                throw new MySelfException("测试异常");
            }

            Console.WriteLine(1 / num);

            Console.WriteLine("木有抛出异常");
        }
    }

//Call:

   class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Exceptions.PersonInfo(null, &#39;男&#39;, 22); 

                // Exceptions.PersonInfo("Purple", &#39;呵呵&#39;, 22);

                Exceptions.PersonInfo("Purple", &#39;男&#39;, 1000);

                //Exceptions.PersonInfo("Purple", &#39;男&#39;, 22);

                Console.WriteLine("代码执行无错误");
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine(e.Message);

                Console.WriteLine(e.StackTrace);
            }
            catch (ArgumentOutOfRangeException e)
            {
                Console.WriteLine(e.Message);

                Console.WriteLine(e.StackTrace);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.Message);

                Console.WriteLine(e.StackTrace);
            }

            Console.ReadLine();
        }
    }

You can see that in the try code block, once the program reaches the throw keyword, it immediately stops running the subsequent code, and then jumps to the catch code block corresponding to the throw exception object type for execution. Therefore, the catch-and-throw model is a more intuitive and reasonable way to handle exceptions.

The above is the compilation of basic knowledge of C#: basic knowledge (13) unusual content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
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
C# as a Versatile .NET Language: Applications and ExamplesC# as a Versatile .NET Language: Applications and ExamplesApr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

C# .NET for Web, Desktop, and Mobile DevelopmentC# .NET for Web, Desktop, and Mobile DevelopmentApr 25, 2025 am 12:01 AM

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.

C# .NET Ecosystem: Frameworks, Libraries, and ToolsC# .NET Ecosystem: Frameworks, Libraries, and ToolsApr 24, 2025 am 12:02 AM

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.