C# language: Exceptions

in #programming6 years ago

CC.png

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.

wyjatek.png

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:

int a = int.Parse(textBox1.Text);

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:

tryeng.png

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.

exe.png

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:

finaeng.png

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 blog http://devman.pl/csharplan/c-language-exceptions/

If you recognise it as useful, share it with others so that others can also use it.

Leave upvote and follow and wait for next articles :) .

That’s it, see you!

Coin Marketplace

STEEM 0.30
TRX 0.11
JST 0.034
BTC 66499.54
ETH 3203.31
USDT 1.00
SBD 4.14