C# language: Exceptions

Hi, today I will explain what are the exceptions, you meet with them every time when some error pops up, if you want to know more then I invite you to read

The exception occurs, for example, if in a line of code you forget a semicolon, then something like this appears:

; expected

If we were doing an application in which, for example, in some place, user have to enter a number and that we would not handle it if the user entered a letter, have would pop out error.

And yet you can exchange it for a message for a user in the style eg You must enter a number!

How to do it, to learn it, let’s create a new project, as I showed it in the first lesson about dictionaries, drag the Textbox control on the form and double-click on it to create its function.

First, you must set this control so that it accepts only numbers, let’s do it in the function of this control using this line:

From now on in this control you can only enter numbers, and what if the user enters a letter then it will pop out what I first showed, in order to handle it we must enter something like:

To handle the exceptions is the try catch function (there is also a finaly function, but we’ll go to that soon), it works so that if in some line of code we expect an error (in our case it’s a line that only accepts number) we give it to the try function when an error occurs, the try function will detect it up and the catch function will execute, i.e. if the user enters a letter, the try function will catch it and then the catch function will be executed.

We can also specify the type of exception in the catch function and display it on the screen in this way.

This allows the code to access the object of this exception. However, it seems to me that this first method will be more user friendly ..

Now use the finally block, it is executed regardless of whether an exception was thrown or not, it is saved in this way:

trzecia funkcja do obsługiwania wyjątków 'finally'

And this are all the most important things you should know about the exceptions, they are useful when, for example, when from application uses a not-too-clever user and clicks anywhere.

This content also you can find on my steemit blog: https://steemit.com/programming/@slawas/c-language-exceptions

And on medium: https://medium.com/@sawomirkowalski/c-language-exceptions-373b7318742d

That’s it, see you!

 
If that post was useful for you share it with your friends :)

Post a comment

Be first!

avatar
  Subscribe  
Notify about