Try And Except In Python

In this tutorial, we will see try and except statements, these statements are used for debugging, apart from try-except statements, we will also look at error types.

What Are Errors And How Many Types?

errors list us the problems in the program. The red text you see on the console is called an error, the type of error is written first, and then the cause of the error.

Types of errors are divided into 3, which are classified as typos, system errors, and logic errors.

  • Typos Error: Spelling errors occur when the syntax of the programming language is not followed.
  • System Error: These are errors in the operating system (errors such as excessive ram usage)
  • Logic Error: This error occurs when output different from the desired output occurs.

I will not all mention the errors here, articles about the errors will be uploaded, it is enough if we know what we will use.

What Is Try And Except Statements?

You can manage errors with try and except structures, print your own error messages, and check the structures that may cause errors. There is a very simple syntax, but still, managing errors can be tiring sometimes, so we will work with about 5 different examples with errors in this article.

Statement Syntax

try:
   # Code
except:
   # Code

First, the try section works, and if an error is found except is work if there is no error, except part is skipped. This statement is similar to conditional statements.

Try Except Statement Practices

In the first example, we will ask the user for an integer. If a value other than an integer comes in, let’s print the message “You must type an integer”.

try:
   x = int(input(":"))
except:
   print("You must type integer")

When there is a different error, this structure does not return that error, for this, you can customize your structures according to the errors.

Here we have printed a customized error message for both types of errors, sometimes we may want to give a crash notification to the user. for this, you can create a crash report. Let’s create a custom crash report.

Creating Crash Report With Try Except

Now, we going to create a crash report, for this, we need to basic program you can download practice code in article blow.

Also, you can create another crash report for another exception and multiple exceptions. Now we going to create a critical error report system, we can use this reporting system when disrupting the program.

Above, we created a basic read file program, if you don’t have any file but you typing this file you see a critical error in the console. The last word, you should use try and except for user because everyone is not a programmer and we must show to truth way.

Congratulations You Finished This Python Tutorial (Don’t Stop And Read Another Article In Below)

Leave a Reply

Your email address will not be published. Required fields are marked *