Day 10 of #100DaysOfCode in Python: Mastering Error Handling

Elshad Karimov
3 min readOct 2, 2023

Congratulations on completing two weeks of your #100DaysOfCode journey with Python! As you’re diving deeper into the language, you’ll encounter scenarios where your code may not execute as expected. That’s where the power of error handling comes in. Today, we’re focusing on understanding, catching, and handling exceptions to ensure your Python programs are robust and reliable.

Understanding Exceptions in Python

In Python, an exception is an event that occurs during the execution of a program, signaling that an error has occurred. Python is equipped with a built-in exception handling mechanism that allows programmers to manage exceptions effectively and ensure that the program can continue its execution or terminate gracefully.

Types of Built-in Exceptions

Python has numerous built-in exceptions, such as:

  • ValueError: Raised when a built-in operation or function receives an argument with the right type but inappropriate value.
  • TypeError: Raised when an operation or function is applied to an object of an inappropriate type.
  • IndexError: Raised when a sequence subscript is out of range.

Handling Exceptions with Try and Except

You can catch and handle exceptions using the try and except blocks. Code that can potentially raise an exception is placed inside the try block, and the code to handle the exception is written in the except block.

try:
# Code that may raise an exception
number = int(input("Enter a number: "))
except ValueError:
# Code to handle the exception
print("Please enter a valid integer!")

The Else and Finally Clauses

The Else Clause

You can use the else clause to define a block of code to be executed if no exceptions were raised in the try block.

try:
number = int(input("Enter a number: "))
except ValueError:
print("Please enter a valid integer!")
else:
print(f"You entered {number}")

The Finally Clause

The finally clause lets you execute code, regardless of the result of the try- and except blocks. It’s mostly used for cleanup actions.

try:
number = int(input("Enter a number: "))
except ValueError:
print("Please enter a valid integer!")
else:
print(f"You entered {number}")
finally:
print("Execution completed!")

Creating Custom Exceptions

You can define your custom exceptions to raise and catch specific errors in your application. Custom exceptions are derived from the built-in Exception class or one of its subclasses.

class InvalidAgeError(Exception):
pass
age = int(input("Enter your age: "))
if age < 0:
raise InvalidAgeError("Age cannot be negative!")

Challenges for Day 10

  1. Identify and Handle Exceptions: Write a program that takes user input, performs an operation, and handles at least two types of exceptions.
  2. Custom Exception: Create a custom exception for a specific error in your application, catch it, and handle it.
  3. Exploration: Research more on Python’s built-in exceptions and practice handling some of them.

Concluding Week 2

Exception handling is an integral aspect of professional Python programming. As you practice handling errors, you’ll find your confidence growing; you’ll be prepared to tackle real-world projects, making your code more robust and reliable. Celebrate the progress made and anticipate the new learning adventures awaiting you! Keep coding confidently! ✨

--

--

Elshad Karimov
Elshad Karimov

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet