Python

Exception Handling in Python

Click for All Topics

Exception Handling in Python

Exception handling is utilized in programming to effectively manage and respond to unexpected errors or exceptional situations that may arise during the execution of a program.

These situations can disrupt the normal flow of a program and cause it to terminate abruptly.

  • Try: Attempt a risky code block for errors.
  • Except: Handle errors that occur in the “try” block.
  • Else: Execute code when no errors arise in the “try” block.
  • Finally: Execute code, regardless of success or errors in the “try” and “except” blocks.

Example –

				
					try:
    number = int(input("Enter a number: "))
    result = 10 / number
except ZeroDivisionError:
    print("Error: Division by zero!")
except ValueError:
    print("Error: Invalid input. Please enter a number.")
else:
    print("Result:", result)
finally:
    print("Execution complete.")


# Output 
# Enter a number: 0
# Error: Division by zero!
# Execution complete.
				
			

Explanation:

  1. Within the try block the code is written to obtain user input and perform a division operation.
  1. If a ZeroDivisionError occurs, the corresponding except block will be executed
  1. Similarly If a ValueError occurs, the corresponding except block will be executed
  1. If there is no error in the code than else block will get executed
  1. No matter whether there is error in code or not finally will get executed at the end.

 

Let’s explore the concepts of try, except, else, and finally in handling errors in programming:

 

  1. Try Block: The “try” block is used to enclose a section of code that might raise an exception. Inside the “try” block, you place the code that could result in an error under certain circumstances

 

💡Note: Without the try block, the program will fail to operate and generate an error.

				
					except ZeroDivisionError:
    print("Error: Division by zero!")
else:
    print("Result:", result)
finally:
    print("Execution complete.")

# Output -
# File "/home/main.py", line 1
   # except ZeroDivisionError:
  #  ^^^^^^
# SyntaxError: invalid syntax
				
			
  1. Except Block: The “except” block follows the try block and specifies how the program should handle specific types of exceptions. If an exception occurs within the try block and it matches the type specified in the except block, the code inside the except block is executed.

 

a. Try-Except

				
					#The try block will generate an exception, because y is not defined:
try:
  print(y)
except:
  print(" exception ")

# Output -
# exception 
				
			

b. Many Exceptions:

 

You have the flexibility to define multiple exception blocks as needed, allowing you to execute specific code for distinct types of errors.

 

Example –

				
					try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Error: Division by zero!")
except ValueError:
    print("Error: Invalid input. Please enter a number.")

# Output -
# Enter a number: 0 1 a
# Error: Invalid input. Please enter a number.
				
			
  1. Else Block: The else block is optional and comes after the try and except blocks. It’s executed when no errors occur in the try block. This is where you can put code that should run if everything goes smoothly.

 

Example –

				
					try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Error: Division by zero!")
except ValueError:
    print("Error: Invalid input. Please enter a number.")
else:
    print("Result:", result)

# Output -
# Enter a number: 20
# Result: 0.5
				
			
  1. Finally Block: The finally block is also optional and appears after the try and except blocks. It gets executed regardless of whether an error occurred or not. It’s useful for tasks that need to be done no matter what, like closing a file or releasing resources.

 

a. Try-except-else-finally:

				
					try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Error: Division by zero!")
except ValueError:
    print("Error: Invalid input. Please enter a number.")
else:
    print("Result:", result)
finally:
    print("Execution complete.")

# Output -
# Enter a number: 2
# Result: 5.0
# Execution complete.
				
			

b. Try-except-finally:

				
					try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Error: Division by zero!")
except ValueError:
    print("Error: Invalid input. Please enter a number.")
finally:
    print("Execution complete.")

# Output -
# Enter a number: b
# Error: Invalid input. Please enter a number.
# Execution complete.
				
			

Error:

An error refers to a situation where the code you’ve written cannot be executed as expected due to various reasons. 

Note: An error in Python refers to a situation where something goes wrong during the execution of your code where as an exception in Python is a specific type of error that occurs during the execution of your code and disrupts the normal flow of the program.

💡Why it is called exception handling and not error handling?

Exception handling is specifically called that way because it focuses on handling exceptional situations or events that occur during the execution of a program, rather than just general errors. While errors are a subset of exceptions, not all exceptions are necessarily errors.

Types of Errors :

  1. SyntaxError: This error  occurs when code is not written correctly according to Python’s rules.
  1. TypeError: This error occurs when you use something in a way that doesn’t match what’s expected.
  1. NameError: This error occurs when you try to use a name (variable or function) that doesn’t exist.
  1. IndexError: This error occurs when you ask for something that’s not in a list or sequence.
  1. KeyError: This error happens when you search for a key (like a dictionary word) that’s not there.
  1. ValueError: This error pops up when you give something a value it can’t handle.
  1. AttributeError: This error occurs when you ask an object to do something it can’t do.
  1. IOError: This error appears when something goes wrong with reading or writing files.
  1. ZeroDivisionError: This error happens when you try to divide a number by zero.
  1. ImportError: This error occurs when you can’t find or use a module or package in your code.

Raise Exception:

The raise statement is like you telling the computer, “Okay, now I want this specific problem to happen!” It’s a way for you to make your program show a certain error or issue on purpose.

Raising an exception” means you’re making your program stop and say, “Hey, something’s not right!“.

Here’s a simple example:

Imagine you’re making a robot that serves drinks. If someone asks for a drink that the robot doesn’t know, you want the robot to say, “I don’t have that drink.” That’s like raising an exception. You’re telling the robot, “Hey, this isn’t right, let’s handle it!”

Code –

				
					drink_menu = ['water', 'soda', 'juice']

def serve_drink(choice):
    if choice not in drink_menu:
        raise Exception("I don't have that drink.")
    else:
        print("Here's your", choice)

user_choice = input("Please choose a drink: ")
try:
    serve_drink(user_choice)
except Exception as e:
    print("Sorry, an error occurred:", e)

# Output -
# Please choose a drink: wine
# Sorry, an error occurred: I don't have that drink.
				
			

Explanation:

  1. If the user asks for a drink not in the menu, the serve_drink function raises an exception.
  1. This makes the program jump to the except block, which handles the situation and gives an error message.

Comparison of the advantages and disadvantages of exception handling:
Advantages of Exception Handling Disadvantages of Exception Handling
Effective error management Increased code complexity
Facilitates debugging Overuse leading to unclear control flow
Improves user experience May hide underlying issues
Provides controlled program flow Complicates debugging
Encourages modular code Dependency on documentation