Thanks to theidioms.com

Learn Python for Data Science (Course I)

Learn Python for Data Science (Course I)

Errors and Exceptions in Python

In this chapter, we will learn about when and why various errors and exceptions in Python. We will also discuss different ways to handle them.

Syntax Errors

Syntax errors, also known as parsing errors, are errors where the parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected.

>>> while True print('Hello world') 
   
File "", line 1
    while True print('Hello world')
                    ^
SyntaxError: invalid syntax 

Exceptions

Even if a statement or expression is syntactically correct, it may cause an error while executing it. Such errors detected during the program execution are termed as exceptions.

>>> 10 * (1/0)
Traceback (most recent call last):
File "", line 1, in 
ZeroDivisionError: division by zero   

Try-Except Statements

Python provides a set of statements that can be used to handle such errors and exceptions in Python. It is like try catch blocks used in other programming languages such as C, C++, and Java.

Syntax:

try:
    # Code to be executed by default
except:
    # Code to be executed if try block fails to be executed

The try-except statement consists of two parts: Try and Except. It works as follows:

  • The try part of the statement consists of a set of code to be executed.
  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.
  • If an exception occurs in any part of the code in the try statement, the rest of the code is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
# Simple example of handling value error exception

while True:
    try: 
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops! That was not a valid number. Try again!")
OUTPUT:
Please enter a number: dsa
Oops! That was not a valid number. Try again!
Please enter a number: 5

In this chapter, we discussed different errors and exceptions in Python. In the upcoming chapter, we will dive deeper into the concepts of Object-Oriented Programming through a lesson on Classes and Objects.

Leave your thought here

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

Close Bitnami banner
Bitnami