Python Exceptions

excepciones en python exceptions in python
k

02/10/2025

Python Exceptions

Python Exceptions handling is essential if you want to develop robust and unbreakable programmes. In short, exception handling in Python is the process of responding to unexpected situations that arise during programme execution.

On the other hand, we have to differentiate between an exception and a syntax error. Both situations are common in Python. A syntax error occurs when we write code that is incorrect, so the Python interpreter cannot process it and gives an ‘error’, while an exception occurs when the code we have written is correct from a syntax point of view, but its correct execution produces an error. Let's look at an example of each for a better understanding.

Py

//Syntax error
# we define a variable a
a = "16' SyntaxError unmatched: undeterminated string literal

//Excepcion
# divide a number by 0
division = 20 / 0
ZeroDivisionError: division by zero

In the previous example, if we make a syntax error in the definition of variable a, since we have put ‘ and on the other hand ' , this will give us an error in Python and the programme cannot continue. Hence the message from the Python interpreter ’SyntaxError unmatched: undetermined string literal".

Below is an example of exceptions in Python. We can see that the syntax of the operation is correct, but executing this code produces an error in the programme when performing the division: ‘ZeroDivisionError: division by zero’. As we know, when we divide a number by 0, the result is infinite.

Therefore, in this post, we will look at how to generate exceptions in Python and how to manage them for greater clarity and fluidity in the programme.

  • Raise
  • Assert
  • Try - Except
  • Try - Except - Else
  • Pass
  • Finally

👉 "Raise"

As mentioned above, there will be occasions when errors occur in our code, so we must be able to manage them to prevent the programme from crashing. Exception handling will help other applications understand your code.

To generate an exception, we will use the keyword “raise”. The syntax is raise exception type (message or description). Once raise is executed, the programme stops executing the rest of the code and exits the programme.

Py

def raise_exception():
     user = input('Insert a number: ')
if not user.isdigit():
raise Exception('You have not entered a number') number = int(user) print(number)

#we call the function
raise_exception()

# If we insert a value different from an integer
Insert a number: hola Exception: You have not entered a number

Above we have the example of the raise_exception() function where the user is asked to enter a number. Then, we convert it to an integer. If the user enters a value other than an integer, as in this case where they have entered the word ‘hello’, then the exception is generated using the raise keyword and the message that follows is displayed. Once this point is reached, the programme stops running.

If we do not establish a way to capture the error that has occurred, then the programme will terminate and send us a standard message for that error. In a way, this is less aesthetically pleasing for the user.

👉 "Assert"

On some occasions, we will use the keyword ‘assert’, which functions as a condition that must be met by the code in order for it to continue executing. If this condition is not met, then the assert exception message is executed, terminating the programme. The syntax for assert is as follows: assert <condition to be checked>.

Py

def raise_input():       
user = input('Insert a number: ') assert int(user).ValueError('A number was not entered') number = int(user) print(number)

#we call the function
def raise_input()

# If we insert anything but an integer Insert a number: hola ValueError: A number was not entered

// Another example
def division(n1,n2):
assert n2 != 0, "You cannot divide a number by 0"
print(n1/n2)

#we call the function
division(5,0)

#Python interpreter response
AssertionError: You cannot divide a number by 0

In the first example above, we see that we set a condition that the value entered by the user must be of type ‘int’, which tells the code to produce a ValueError error and display the message “An integer was not entered”.

In the second example, the condition set is that the number acting as the divisor cannot be equal to 0, as this would cause an infinite result.

👉 Try - Except structure in python exceptions

So far, we have seen exceptions and how to generate them. Now we will use a structure to manage these exceptions. The try-except structure is used to detect and manage exceptions. Python executes the code in the try block and if it finds an error, the code execution will jump to the except block.
The lines of code in the try block after the error will not be executed. If no error occurs, the code in the except block will not be executed. The except block is where exceptions are caught.

In the second example, we can see that there are several except clauses, each establishing a different type of exception.

Py

def square():     
try: user = input('Insert a number: ') number = int(user) print(number**2) except: print('You have not entered a number') #we call the function square() # If we have not entered an integer Insert a number: hola You have not entered a number

// Another example of try - except statement
def divide_numbers(n1,n2):
try:
n1 = input('Insert a number: ')
n2 = input('Insert a second number: ')
one = int(n1)
two = int(n2)
result = one / two
return result
except ValueError:
print('You have not entered two numbers')
except ZeroDivisionError:
print('The divisor number cannot be 0')

In the previous example, we see that in the - try - block we have the code that will be executed first, but if what the user enters is not an integer, then the code stops executing and jumps to the - except - block.

In the second example, in the divide_numbers() function, we have a - try - block where the main code is executed again. In this block, the data entered by the user is collected in the variables n1 and n2. Subsequently, variables one and two store this data converted into integers in order to perform the division in result. Finally, the result of the division - result - is returned.

If any part of the code does not correspond to what is required by the code, for example if n1 or n2 are not integers, then the code stops executing and produces a ValueError exception, or if n2 is 0, then the exception will be ZeroDivisionError, displaying the corresponding messages.

👉 Try - Except - Else

The structure - try - except - can sometimes have an optional clause - else -. If this clause is present in the code, it must follow all the - except - blocks before being executed. Basically, the - try - block is executed, and if it does not find any exceptions, then the - else - block is executed.

Let's look at an example where we define a function called open_file() that will open a file in the try block. If it does not find any errors, then the else block is executed. But if it finds an error, the except block is executed, sending a message to the user and stopping the code from executing at that point.

Py

def open_file(path):  
try: file = open(path) except FileNotFoundError: print('No such file located in: ', path)
else:
print(file.read()) #we call the function path = 'python.txt'
open_file(path)

Let's analyse the code in the example. On the one hand, we have a function called open_file() that takes a parameter called path, which corresponds to the location of the file we want to access.

In the try block, we attempt to open that file by accessing the location that has been passed to us as a parameter file = open(location). If that location is correct and there is indeed a file called python.txt, which we see below when we call the function, then we will not encounter the FileNotFoundError error and the code will continue to the else block, where it will print the contents of that python.txt file.

If, on the other hand, there is no file named python.txt at that location, it will print the message from the except block and the code will end there without executing the else block.

👉 Pass

On certain occasions, we can use the keyword pass. When pass is executed, “nothing” happens. It is like a comment in the code, but with the difference that the interpreter does read pass, which it does not do with comments.

Pass is useful as a placeholder when an instruction is required from a syntactical point of view, but no code needs to be executed.

Py

def open_file(path):   
try: file = open(path) except FileNotFoundError: pass
else:
print(file.read())
print('Check the right location of your file') #call the function path = 'python.txt'
open_file(path)

The code is practically the same as in the previous example, but with the difference that if there is an error in the code, such as the file not being in the correct location, the - except - block will not be activated because it has - pass - which allows the code to continue executing. In this case, the programme continues to run and no error message is displayed, nor is the print(file.read()) code executed. Instead, print(“Check the right location of your file”) will be executed, which is the message that the user will see on their screen.

👉 Finally

Finally, we have another option in - finally - with regard to exception handling in Python. It is generally used to clean up actions that must be executed in any circumstance, such as in the previous case, to close an open file. It is executed as the last task before the try statement ends. And it is executed regardless of whether an exception has occurred or not.

Py

def division(n1,n2):     
try:
result = n1 / n2 except ZeroDivisionError as e: print(e) else: print('The result is: ', result) finally: print('The programme has finished') #we call the function division(4,8)

In the previous example, we used the finally block to confirm that the code has been executed, regardless of whether there was an error or not.

In short, Python offers us the option to manage exceptions, which can be very useful for making our code robust. Once you have more knowledge of the Python language, they will be very helpful.

To learn Python with practical exampls is fundamental to be able to program in Python. If you want to continue learning how to program in Python, you can find more resources in this link. Creatuwebpymes, is a web design and web positioning company in the Canary Islands that ❤️ programming.

Other Posts in our Blog

creatuwebpymes quien somos

Francisco Brito Diaz

CEO de creatuwebpymes.com, empresa de diseño web y marketing digital en Canarias.