Exception handling in c with example LEARNOVITA

C# Exception Handling Tutorial | Learn with Best Practices

Last updated on 12th Aug 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 of WPF, XML, REST, Agile, V model, C#, SQL server, Web API, and ASP.NET.

(5.0) | 17521 Ratings 2116

Introduction to C# – Exception Handling:

A special case is associate degree undesirable or unforeseen occasion, that happens throughout the execution of a program i.e. at runtime, that upsets the normal progression of the program’s directions. Some of the time throughout the execution of the program, the shopper may confront the probability that the program may crash or show a shocking occasion throughout its runtime execution. This undesirable occasion is thought as an associate degree Exception and it for the foremost half offers the register regards to one thing wrong within the code.

Exception Handling in C#:

Here, you may ascertain with regards to exemption taking care of in C# utilizing try, get, finally impedes. Exemptions within the application ought to be taken care of to forestall the blood of the program and shocking outcomes, log special cases and proceed with totally different functionalities. C# offers worked in serving to to cope with the special case exploitation strive, catch & finally blocks.

Sentence structure:

  • place the code here that may raise exemptions
  • }
  • get
  • at long last

Attempt block: Any speculated code that may raise special cases got to be placed within a try block. Throughout the execution, presumptuous a special case happens, the progression of the management leaps to the primary matching catch block.

Get block: The catch block is AN exemption controller block wherever you’ll play out some activity like work and inspecting a special case. The catch block takes a boundary of a special case kind utilizing that you’ll get the subtleties of AN exemption.

At long last block: The ultimate block can forever be dead whether or not or not a special case is raised. Ordinarily, a final block got to be used to deliver assets, e.g., to shut any stream or document protests that were opened within the strive block. future could toss a special case on the off probability that you simply enter a non-numeric person.

Exception Handling in C#
  • Model: C# Program
  • class Program,
  • is ”);
  • }
  • }

Special case Filters: You can utilize multiple catch blocks with completely different special case sort boundaries. These area units are referred to as special case channels. Special case channels are valuable once you have to be compelled to influence numerous styles of exemptions in numerous ways.

Invalid catch Block: A parameterless catch block and a catch block with the Exception parameter don’t seem to be permissible within the same try-get proclamations, since the 2 of them are constant factors.

At long last Block: The final block may be a discretionary sq. and may come back when an attempt or get the block. the ultimate block can forever be dead whether or not or not a special case happened. the ultimate block for the foremost half utilized for tidying up code e.g., discarding unmanaged objects.

Settled try get: C# permits are settled and try to get blocks. whereas utilizing settled try get blocks, a special case is going to be at bay within the 1st matching catch block that follows the attempt block wherever associate degree exemption happens.

Exemption Clauses in C#:

  • C# exemptions area units addressed by categories. The exemption clauses in C# area unit primarily foursquare or by implication got from the System.Exception category. a little of the exemption categories got from the System.
  • The System.Application Exception and System.SystemException categories.
  • The System.Application Exception category upholds exemptions created by application programs. Consequently, the exemptions characterized by the developers need to be from this category.
  • The System.System Exception category is the base category for all predefined framework exemptions.
  • The related table provides a little of the predefined exemption categories from the System.System Exception category.

Special case category and outline In the previous sections we’ve seen that case categories may be wont to accomplish info aggregation, and conjointly however categories may be wont to accomplish information abstraction or to outline stateful objects.

Taking care of Exceptions:

C# provides an Associate in Nursing organized account of the special case coping with try and catch blocks. Utilizing these squares the middle program explanations area unit isolated from the blunder coping with articulations.These mistake-taking care of squares area unit dispensed utilizing the attempt, catch, and eventually keywords. Making User-Defined Exceptions: you’ll be able to likewise characterize your exemption. shopper characterized special case categories area unit gotten from the Exception category.

Tossing Objects: you’ll be able to toss Associate in Nursing items if it’s either foursquare or in an exceedingly detour gotten from the System. Exception category.

The distinction among Errors and Exception:

Error: Mistakes area unit stunning problems that may emerge throughout computer program execution. Mistakes can’t be taken care of. All Errors area unit special cases.

Special cases: Special cases area unit unforeseen occasions that may emerge throughout run-time. Exemptions may be restricted utilizing try get instruments. All exemptions don’t seem to be mistakes.

Special case Hierarchy: In C#, each one of the special cases is gotten from the bottom category Exception that gets in addition partitioned off into 2 branches as Application Exception and another is System Exception. System Exception may be a base category for all CLR or program code-created errors. Application Exception may be a base category for all application-related exemptions. All the special case categories are unit foursquare or by implication got from the Exception category. If there is an Application Exception, the shopper would possibly build its exemption varieties and categories. Yet, System Exception contains all the realized special case varieties like Divide by Zero Exception or Null Reference Exception, etc.

Unhandled Exception:

  • System.IndexOutOfRangeException:
  • The index was on the far side of the exhibit.
  • at GFG.Main (System.String[] args) [0x0002e] in :0
  • [ERROR] FATAL UNHANDLED EXCEPTION:
  • System.IndexOutOfRangeException:
  • The index was on the far side of the cluster.
  • at GFG.Main (System.String[] args) [0x0002e] in :0

Client outlined Exceptions: Client characterized special cases square measure valuable once we ought to code Associate in Nursing exemption which will not be characterized by the language. For example, in the Associate in Nursing engine compartment, if the temperature transcends some edge, the hotness ought to be converted. For seeing however shopper characterized exemptions square measure used we tend to take Associate in Nursing illustration of a division by nothing. Here we tend to characterize a category DivByZero that acquires from Exception and is termed by the DivisionOperation work once the divisor is corresponding to nothing. Since they need the capability it might toss a special case in its place within the tried block. A catch block is characterized to urge any exemption of sort Exception and therefore the Message property prints the type of special case that went on.

Standard Exceptions: There square measure 2 types of special cases: exemptions created by Associate in Nursing capital punishment system and special cases made by the conventional language runtime. System.The exception is that the base category for all exemptions in C#. a couple of special case categories acquired from this category together with ApplicationException and SystemException. These 2 categories structure the explanation for many different runtime special cases. totally different special cases that get foursquare from System. Exceptions incorporate IOException, WebException, then forth.

he normal language runtime throws SystemException. The ApplicationException is tossed by a shopper program instead of the runtime. The SystemException incorporates the ExecutionEngineException, StackOverFlowException then forth. It isn’t urged that we tend to get SystemExceptions neither is it nice programming 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 numerous forms of exemptions that may be created within the C# program:

Partition By Zero exemption: It happens once the consumer endeavors to separate by nothing

Out of Memory special cases: It happens once then, at that time, the program makes an attempt to utilize extreme memory

List out of certain Exception: Accessing the cluster element or list that is absent in it.

Stack overflow Exception: Mainly caused owing to the limitless formula method

Invalid Reference Exception: Occurs once the consumer endeavors to reference a commentary that’s of the NULL kind. what’s a lot of some a lot of.

Invalid Reference Exception

C# Scope of exemption dealing:

In .net, once associate degree exemption happens, the framework can look around the nested attempt blocks on the stack to determine whether or not there’s a catch block that may get the special case. This happens before any final blocks run. If there isn’t any sq. that may get the exemption, the framework can summon an associate degree “unhandled special case” controller while not running any final blocks. Assuming the framework that verifies that there’s a sq. that may get the special case, it’ll begin loosening up the stack and run finally blocks connected with inner attempt blocks till probably it’s disentangled up the stack the full thanks to the catch block is found, or associate degree exemption gets tossed within the execution of a final block. Within the last circumstance, the past exemptions are deserted and not handled further; special cases taken care of can begin yet again with the recently tossed exemption.

Even though there’s a linguistics distinction between wanting to catch a special case, versus simply wanting to follow au courant it (yet let or not it’s viewed as uncaught), there’s no spick methodology for human activity that qualification in C#; code that gets associate degree exemption is relied upon to see it. Everything one will manage in C# is to use a catch (indicating to the framework’s special case handling explanation to suppose one can get the exemption) and subsequently use a throw, to demonstrate one would rather not resolve all things thought-about (this can happen when internal “at last” blocks have run). During a few completely different dialects, as an example, vb.net, it’s possible to follow au courant special cases, while not obtaining them, before finally blocks run. While there don’t seem to be a myriad of things where a catch and throw isn’t identical as catching a special case while not catching it, there don’t seem to be several things wherever the qualification matters. assumptive one is utilizing C# and one desires to abstain from being unfriendly to encompassing code that ought to catch exemptions from inward code before finalizer blocks run, the most effective methodology is presumably to compose a special case taking care of covering strategy written in vb (or have another person build it happen), order it to a DLL, and subsequently, use lambdas to require care of such a capability technique for it to summon within associate degree acceptable attempt/channel/get/at last sq.

Properties of the Exception Class:

The Exception category has varied properties that assist the consumer with obtaining knowledge concerning the exemption throughout the special case.

Data: This property assists with obtaining info} concerning the discretionary information that is controlled by the property within the key-esteem sets.

Target Site: This property assists with obtaining the name of the strategy wherever the special case can be tossed.

Message: This property assists with giving insights concerning the first driver of the exemption event.

Help Link: This property assists with holding the universal resource locator for a selected exemption.

Stack Trace: This property assists with giving the information concerning wherever the error happened.

Inner Exception: This property assists with giving the information concerning the series of exemptions which will have happened.

Framework Level Exception:

Framework special cases are obtained from the bottom category System.SystemException that in itself could be a determined category of SystemException. A System Exception happens once a deadly or non-recoverable mistake is toughened, like associate degree info base accident, certain blunders, and so on

Application-Level Exception:

  • Application-level exceptions are obtained from the bottom category System.ApplicationException is likewise a determined category of SystemException. associate degree Application-level special case happens once a redeemable blunder is toughened, as an example, some unacceptable quite data info, number-crunching exemptions, and then forth These are consumer characterized exemptions tossed by the appliance and for the foremost half, the program will continue back to its typical course of directions within the wake of sinking this kind of special case.
  • In any run-of-the-mine application, Exceptions are by and enormous forbidden at the code level utilizing try get blocks. On the off chance that the code doesn’t have a trial and catch block for the happened exemption then it proliferates to the page level, at page level the Page Error routine may be used to wear down the special case. On the off probability that the error is up to now not taken care of at the page level then the blunder at long last engenders to the appliance level. At the appliance level, we have a tendency to use the worldwide.aspx file to write The distinction between System Level Exception and Application-Level Exception in C#:
  • A special case is Associate in Nursing undesirable or shocking occasion, that happens throughout the execution of a program i.e. at runtime, that disturbs the everyday progression of the program’s pointers. Currently and once more throughout the execution of the program, the consumer would possibly confront the probability that the program would possibly crash or show a shocking occasion throughout its runtime execution.
  • This undesirable occasion is thought as Associate in Nursing Exception and is for the foremost half given the sign up regards to one thing wrong within the code. In C# a special case will be a System or Associate in Nursing Application-Level exemption.

Benefits of Exceptions:

Separating Error-Handling Code from “Standard” Code: – Exceptions offer the mandatory resources to isolate the subtleties of a way to treat one strange thing that happens from the principal principle of a program. In standard programming, blunder location, revealing, and taking care of often cause unsupportive alimentary paste code. Special cases empower you to compose the basic progression of your code and to manage the uncommon cases elsewhere.

Propagating Errors Up the Decision Stack: – The second good thing about special cases is that the capability to unfold mistakes asserting up the decision pile of methods.

Grouping and Differentiating Error Types: – as a result of all special cases tossed within a program are objects, the gathering or ordering of exemptions could be a characteristic result of the category progressive system.

Conclusion:

On the off likelihood that you just don’t place the piece of code that you just assume would possibly bring Associate in Nursing exemption up within the future within the try get blocked, then, at that time, your program could cut back abnormally and it’ll be onerous enough for you or any designer to follow the blunder back to the ASCII text file and fix it.

Are you looking training with Right Jobs?

Contact Us

Popular Courses

cc