4.5 Errors



Introduction

 We can identify several types of errors that we encounter in computer programming.

Syntax errors are faults in programming language use. Each programming language has its own syntax, which we must follow.

 Runtime errors occur when a script or function is being executed. These are also known as "execution time errors." We'll see some examples of them soon.

 Logical mistakes do not provide error messages, but they do produce unexpected or incorrect output.


Syntax Errors

Refer to the example below. We are trying to print the string "Hello World!" to the console.

So, what happens if we execute this code? It will provide a "Syntax Errorhis code? It will produce a "Syntax Error." We attempted to output a string value, but Python expected single or double quotation marks. However, one quote mark was missed at the end of the sentence by accident. Python is complaining about a "syntax error" as a result.

print(‘Hello World)

 


Runtime Errors

Runtime errors arise when otherwise correct Python code produces problems at runtime. An error notice will appear informing us of what went wrong.

It is critical to understand that if a runtime error occurs and is not handled appropriately, your Python program will terminate. That is, the software will not continue to run and you will be unable to complete the desired job.

In Python, there are several forms of runtime errors.




Name Error

A "NameError" happens when you attempt to refer to a variable that is not specified in the code. In the example, there is a variable named "number" with the value 10. Then we attempt to print the value of the variable "num." As a result, Python complains about a name problem, stating that "name "num" is not defined."

number = 10

print(num)



IndexError

This error happens when we try to access a value from a sequence but the referenced index is out of range. In this example, my_list only has three items, the index is ranging from 0 to 2. But we are trying to access the item at index 10, which is not available. That is why Python is raising an index error.

num_list = [1,2,3]

                       print(num_list[10])

 



Type Error

A type error occurs when we try to perform an operation on variables or objects of an inappropriate type. In this case, we are causing a type mismatch. In the example, we are trying to perform the "plus" operator on a string and an integer. Therefore, Python is complaining that it can only concatenate (join) a string to another string but not to any other data type (in this case, an integer).

                        str_name = 'colin' + 1

            print(str_name)

 


Value Error

When a built-in operation or function gets an argument with the correct type but an erroneous value, a value error occurs. In this scenario, we are attempting to print an integer number while supplying the string value "hello" to the function "int," which is incorrect. That is why Python is reporting a value problem.

print(int('hello'))

 


 Import Error / ModuleNotFound Error

In this example code, we are trying to import a module named "new_module," which does not exist. Therefore, Python is raising a "Module Not Found" error. A similar error could occur if you try to import something that does not exist from an existing module.

                     import new_module




Handling Runtime Errors

As previously explained, if a runtime error occurs, the application will terminate instantly if the issue is not handled appropriately. As a result, we must carefully prepare to "catch" and manage any potential mistakes during runtime. That manner, we can keep our software running without interruption.


The try/except Structure

The try/except structure assists us in dealing with potential runtime issues. This does not imply that we can avoid making mistakes. Instead, it provides a safe path for the program to follow in the event of a runtime error.

In this structure, we can basically distinguish two blocks (try and except). The so-called "dangerous code" can be placed in the try block. That indicates that you are expecting an error in that part of code. If the error happens, the program goes to the except block, performs what is inside that block, and then continues with the program.

It's worth noting that if we don't utilize this error-handling structure, the application will crash as soon as the problem occurs.


Example

A basic try/except structure is shown below. We are expecting a number from the user in this software. After receiving some input, the application will attempt to convert it to an integer value. It is a dangerous surgery. We cannot guarantee that the user will supply a phone number.

For example, the user can enter a string or nothing at all. The software will have difficulty converting anything other than a number to an integer in this situation. In most cases, the software will protest about the problem and then exit. In our example, however, in such a case, the program will move to the unless block and give the value -1 to the variable num val.


num_input = input('Enter a number:')

 

try:

                        num_val = int(num_input)

except:

                        num_val = -1

 

if num_val > 0:

                         print('A number was entered!')

else:

                        print('Not a number!')