C# Exception Handling Tutorial | Learn with Best Practices
C Exception Handling Tutorial ACTE

C# Exception Handling Tutorial | Learn with Best Practices

Last updated on 28th Jan 2022, Blog, Tutorials

About author

Jagan Mohan (Senior C# Developer )

Jagan Mohan is a Senior Senior C# Developer and has extensive knowledge in the following areas: WPF, XML, REST, Agile, V Model, C#, SQL Server, Web API, ASP, and.NET.

(5.0) | 18624 Ratings 2296
    • Introduction to C# – Exception Handling
    • Sentence structure
    • Model: C# Program
    • Special case Filters
    • Exemption Clauses in C#
    • Special case Class and Description
    • Taking care of Exceptions
    • The distinction among Errors and Exception
    • Special case Hierarchy
    • Unhandled Exception
    • Client Defined Exceptions
    • Different Exception Classes
    • C# Scope of exemption dealing
    • Properties of the Exception Class
    • Framework Level Exception
    • Application-Level Exception
    • The contrast between System Level Exception and Application-Level Exception in C#
    • Benefits of Exceptions
    • Conclusion

    Subscribe For Free Demo

    [custom_views_post_title]

      Introduction to C# – Exception Handling:

    • A special case is an undesirable or unforeseen occasion, which happens during the execution of a program i.e. at runtime, that upsets the ordinary progression of the program’s directions.
    • Some of the time during the execution of the program, the client might confront the likelihood that the program might crash or show a surprising occasion during its runtime execution.
    • This undesirable occasion is known as an Exception and it for the most part gives the sign in regards to something wrong inside the code.

    • Exemption Handling in C#:

    • Here, you will find out with regards to exemption taking care of in C# utilizing attempt, get, lastly impedes.
    • Exemptions in the application should be taken care of to forestall the crashing of the program and surprising outcomes, log special cases and proceed with different functionalities.
    • C# offers worked in helping to deal with the special case using try, catch & finally blocks.

    • Sentence structure:

      • Attempt,
      • {
      • // put the code here that might raise exemptions
      • }
      • get
      • {
      • // handle exemption here
      • }
      • at long last
      • {
      • // last cleanup code
      • }

      Attempt block: Any speculated code that might raise special cases ought to be put inside a try{ } block. During the execution, assuming a special case happens, the progression of the control leaps to the first matching catch block.


      Get block: The catch block is an exemption controller block where you can play out some activity like logging and inspecting a special case. The catch block takes a boundary of a special case type utilizing which you can get the subtleties of an exemption.


      At long last block: The final block will forever be executed whether or not a special case is raised. Ordinarily, a final block ought to be utilized to deliver assets, e.g., to close any stream or document protests that were opened in the try block. The next may toss a special case on the off chance that you enter a non-numeric person.


      Model: C# Program

      • class Program,
      • {
      • static void Main(string[] args)
      • {
      • Console.WriteLine(“Enter a number: “);
      • var num = int.Parse(Console.ReadLine());
      • Console.WriteLine($”Squre of {num} is {num * num}”);
      • }
      • }

      Special case Filters:

      You can utilize multiple catch blocks with different special case type boundaries. These are called special case channels. Special case channels are valuable when you need to deal with various sorts of exemptions in various ways.

      Invalid catch Block:

      A parameterless catch block and a catch block with the Exception parameter are not permitted in the same try-get proclamations, since the two of them do the same thing.


      At long last Block:

      The final block is a discretionary square and should come after a try or get the block. The final block will forever be executed whether or not a special case happened. The final block for the most part utilized for tidying up code e.g., discarding unmanaged objects.


      Settled attempt get:

      C# permits settled attempt get blocks. While utilizing settled attempt get blocks, a special case will be trapped in the first matching catch block that follows the try block where an exemption happened.


      Course Curriculum

      Learn Advanced C and C Plus Plus Certification Training Course to Build Your Skills

      Weekday / Weekend BatchesSee Batch Details

      Exemption Clauses in C#:

    • C# exemptions are addressed by classes. The exemption clauses in C# are primarily straightforwardly or by implication got from the System.Exception class. A portion of the exemption classes got from the System.
    • The System.Application Exception and System.SystemException classes.
    • The System.Application Exception class upholds exemptions produced by application programs. Consequently, the exemptions characterized by the developers ought to get from this class.
    • The System.System Exception class is the base class for all predefined framework exemptions.
    • The accompanying table gives a portion of the predefined exemption classes got from the System.System Exception class.

    • Special case Class and Description

      In the previous sections we have seen how case classes could be used to achieve information aggregation, and also how classes could be used to achieve data abstraction or to define stateful objects.


      Taking care of Exceptions:

      C# gives an organized answer for the special case dealing with attempt and catch blocks. Utilizing these squares the center program explanations are isolated from the blunder dealing with articulations.These mistake-taking care of squares are carried out utilizing the try, catch, and finally keywords.

      Making User-Defined Exceptions: You can likewise characterize your exemption. Client characterized special case classes are gotten from the Exception class


      Tossing Objects: You can toss an item if it is either straightforwardly or in a roundabout way gotten from the System. Exception class.


      The distinction among Errors and Exception:

      Error:

    • Mistakes are surprising issues that might emerge during PC program execution.
    • Mistakes can’t be taken care of.
    • All Errors are special cases.

    • Special cases:

    • Special cases are unforeseen occasions that might emerge during run-time.
    • Exemptions can be dealt with utilizing attempt get instruments.
    • All exemptions are not mistakes.

    • Special case Hierarchy:

    • In C#, every one of the special cases is gotten from the base class Exception which gets additionally partitioned into two branches as Application Exception and another is System Exception. System Exception is a base class for all CLR or program code-created errors.

    • Application Exception is a base class for all application-related exemptions. All the special case classes are straightforwardly or by implication got from the Exception class.

    • If of Application Exception, the client might make its exemption types and classes. Yet, System Exception contains all the realized special case types such as Divide by Zero Exception or Null Reference Exception, etc.

    • Unhandled Exception:

      • System.IndexOutOfRangeException:
      • Index was beyond the exhibit.
      • at GFG.Main (System.String[] args) [0x0002e] in <9fa39b3b4dec49eb8af89dc70d5a0618>:0
      • [ERROR] FATAL UNHANDLED EXCEPTION:
      • System.IndexOutOfRangeException:
      • Index was beyond the cluster.
      • at GFG.Main (System.String[] args) [0x0002e] in <9fa39b3b4dec49eb8af89dc70d5a0618>:0

      Client Defined Exceptions:

      Client characterized special cases are valuable when we need to code an exemption that may not be characterized by the language. For instance, in an engine compartment, if the temperature transcends some edge, the hotness should be switched off. For seeing how client characterized exemptions are utilized we take an illustration of a division by nothing.


      Here we characterize a class DivByZero that acquires from Exception and is called by the DivisionOperation work when the denominator is equivalent to nothing. Since they require the capacity it could toss a special case it is put in the attempted block. A catch block is characterized to get any exemption of type Exception and the Message property prints the sort of special case that has happened.


      Standard Exceptions:

    • There are two kinds of special cases: exemptions created by an executing system and special cases produced by the normal language runtime. System.The exception is the base class for all exemptions in C#. A few special case classes acquire from this class including ApplicationException and SystemException.

    • These two classes structure the reason for most other runtime special cases. Different special cases that get straightforwardly from System. Exception incorporate IOException, WebException, and so forth.

    • The normal language runtime tosses SystemException. The ApplicationException is tossed by a client program rather than the runtime. The SystemException incorporates the ExecutionEngineException, StaclOverFlowException and so forth It isn’t suggested that we get SystemExceptions nor is it great programming practice to toss.


    • SystemExceptions in our applications.
    • System.OutOfMemoryException
    • System.NullReferenceException
    • Syste.InvalidCastException
    • Syste.ArrayTypeMismatchException
    • System.IndexOutOfRangeException
    • System.ArithmeticException
    • System.DevideByZeroException
    • System.OverFlowException

    • Different Exception Classes:

      There are various types of exemptions that can be produced in the C# program:

      Partition By Zero exemption:

      It happens when the client endeavors to separate by nothing

      Out of Memory special cases: It happens when then, at that point, the program attempts to utilize extreme memory

      List out of bound Exception:

      Accessing the cluster component or list which is absent in it.

      Stack over flow Exception:

      Mainly caused because of the limitless recursion process

      Invalid Reference Exception:

      Occurs when the client endeavors to reference an article that is of the NULL kind. what’s more some more.


      C# Scope of exemption dealing:

    • In .net, when an exemption happens, the framework will look through the nested try blocks on the stack to decide whether there is a catch block that can get the special case. This happens before any final blocks run. If there isn’t any square that can get the exemption, the framework will summon an “unhandled special case” controller without running any final blocks.

    • Assuming the framework that verifies that there is a square that can get the special case, it will begin loosening up the stack and run finally blocks related with inner try blocks until possibly it has loosened up the stack the whole way to the catch block is found, or an exemption gets tossed in the execution of a final block. In the last circumstance, the past exemption will be deserted and not handled further; special cases taken care of will begin once again with the recently tossed exemption.

    • Even though there is a semantic contrast between needing to catch a special case, versus just needing to follow up on it (yet let it be viewed as uncaught), there is no spotless method for communicating that qualification in C#; code which gets an exemption is relied upon to determine it.

    • Everything one can manage in C# is use a catch (indicating to the framework’s special case handling rationale to think one will get the exemption) and afterward use a throw, to demonstrate one would rather not resolve it all things considered (this will happen after internal “at last” blocks have run). In a few different dialects, for example, vb.net, it is feasible to follow up on special cases, without getting them, before finally blocks run.

    • While there are not countless situations where a catch and throw is not the same as catching a special case without catching it, there are not many situations where the qualification matters. Assuming one is utilizing C# and one wishes to abstain from being unfriendly to encompassing code which should catch exemptions from inward code before finalizer blocks run, the best methodology is most likely to compose a special case taking care of covering strategy written in vb (or have another person make it happen), order it to a DLL, and afterward, use lambdas to take care of such a capacity technique for it to summon inside an appropriate attempt/channel/get/at last square.

    • Course Curriculum

      Get JOB Oriented C and C Plus Plus Training for Beginners By MNC Experts

      • Instructor-led Sessions
      • Real-life Case Studies
      • Assignments
      Explore Curriculum

      Properties of the Exception Class:

      The Exception class has numerous properties which assist the client with getting data about the exemption during the special case.

      Data: This property assists with getting the data about the discretionary information which is held by the property in the key-esteem sets.

      Target Site: This property assists with getting the name of the strategy where the special case will toss.

      Message: This property assists with giving insights regarding the primary driver of the exemption event.

      Help Link: This property assists with holding the URL for a specific exemption.

      Stack Trace: This property assists with giving the data regarding where the mistake happened.

      Inner Exception: This property assists with giving the data about the series of exemptions that may have happened.


      Framework Level Exception:

    • Framework special cases are gotten from the base class System.SystemException which in itself is a determined class of SystemException.
    • A System Exception happens when a lethal or non-recoverable mistake is experienced, similar to an information base accident, bound blunders, and so on

    • Application-Level Exception:

    • Application-level exemptions are gotten from the base class System.ApplicationException is likewise a determined class of SystemException. An Application-level special case happens when a recoverable blunder is experienced, for instance, some unacceptable kind of info information, number-crunching exemptions, and so forth

    • These are client characterized exemptions tossed by the application and for the most part, the program can continue back to its conventional course of directions in the wake of settling this type of special case.

    • In any run-of-the-mill application, Exceptions are by and large dealt with at the code level utilizing attempt get blocks. On the off chance that the code doesn’t have an attempt and catch block for the happened exemption then it proliferates to the page level, at page level the Page Error routine can be utilized to deal with the special case. On the off chance that the mistake is as yet not taken care of at the page level then the blunder at long last engenders to the Application level. At the application level, we use the global.aspx file to overwrite

    • The contrast between System Level Exception and Application-Level Exception in C#:

      A special case is an undesirable or surprising occasion, which happens during the execution of a program i.e. at runtime, that disturbs the typical progression of the program’s guidelines. Now and again during the execution of the program, the client might confront the likelihood that the program might crash or show a surprising occasion during its runtime execution.

      This undesirable occasion is known as an Exception and is for the most part given the sign in regards to something wrong inside the code. In C# a special case can be a System or an Application-Level exemption.


      Benefits of Exceptions:

      Separating Error-Handling Code from “Standard” Code: – Exceptions give the necessary resources to isolate the subtleties of how to treat something strange that occurs from the principal rationale of a program. In conventional programming, blunder location, revealing, and taking care of regularly lead to confounding spaghetti code. Special cases empower you to compose the fundamental progression of your code and to manage the uncommon cases somewhere else.


      Propagating Errors Up the Call Stack: – The second benefit of special cases is the capacity to spread mistake announcing up the call pile of strategies.

      Grouping and Differentiating Error Types: – Because all special cases tossed inside a program are objects, the gathering or ordering of exemptions is a characteristic result of the class progressive system.


      C and C Plus Plus Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      Conclusion:

      On the off chance that you don’t put the piece of code that you think might bring an exemption up in the future inside the attempt get blocked, then, at that point, your program may cut short abnormally and it will be hard enough for you or any designer to follow the blunder back to the source code and fix it.


    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free