DEV Community

Cover image for Python Exception Handling – Day 11
augustineowino357-design
augustineowino357-design

Posted on • Edited on

Python Exception Handling – Day 11

Python Exception Handling

In the previous lesson, we learned about Strings and how they are used to store and manipulate text in Python. Today, we will learn about Exception Handling, which helps programs handle errors gracefully without crashing.

Exception Handling is very important because errors can occur during program execution, especially when dealing with user input, files, or calculations.


What is an Exception?

An Exception is an error that occurs while a program is running.

When an exception occurs, Python stops the program and displays an error message.

Example

number = 10 / 0

print(number)
Enter fullscreen mode Exit fullscreen mode

Output

ZeroDivisionError: division by zero
Enter fullscreen mode Exit fullscreen mode

Why Exception Handling is Important

Exception Handling helps programmers:

  • Prevent program crashes
  • Handle unexpected errors
  • Improve user experience
  • Make programs more reliable
  • Debug applications easily

The try and except Block

Python uses:

  • "try"
  • "except"

to handle exceptions.

Syntax

try:
    # risky code
except:
    # code to handle error
Enter fullscreen mode Exit fullscreen mode

Example of try and except

try:

    number = 10 / 0
    print(number)
Enter fullscreen mode Exit fullscreen mode

except:

    print("An error occurred")
Enter fullscreen mode Exit fullscreen mode

Output

An error occurred
Enter fullscreen mode Exit fullscreen mode

Instead of crashing, the program handles the error gracefully.


Handling Specific Exceptions

Python allows handling specific error types.

Example

try:

    number = int(input("Enter a number: "))
    print(number)
Enter fullscreen mode Exit fullscreen mode

except ValueError:

    print("Invalid input")
Enter fullscreen mode Exit fullscreen mode

Sample Output

Enter a number: abc
Invalid input
Enter fullscreen mode Exit fullscreen mode

Common Python Exceptions

Exception| Meaning
"ValueError"| Invalid value
"TypeError"| Wrong data type
"NameError"| Variable not defined
"IndexError"| Invalid index
"KeyError"| Invalid dictionary key
"ZeroDivisionError"| Division by zero
"FileNotFoundError"| File does not exist


The else Block

The "else" block runs if no exception occurs.

Example

try:

    number = int(input("Enter a number: "))
    print(number)
Enter fullscreen mode Exit fullscreen mode

except ValueError:

 print("Invalid input")
Enter fullscreen mode Exit fullscreen mode

else:

    print("Program executed successfully")
Enter fullscreen mode Exit fullscreen mode

The finally Block

The "finally" block always executes whether an error occurs or not.

Example

try:
    print("Python")

except:
    print("Error")

finally:
    print("Execution completed")
Enter fullscreen mode Exit fullscreen mode

Output

Python
Execution completed
Enter fullscreen mode Exit fullscreen mode

Using Multiple Exceptions

A program can handle multiple exceptions.

Example

try:
    number = int(input("Enter number: "))
    result = 10 / number

    print(result)

except ValueError:
    print("Invalid input")

except ZeroDivisionError:
    print("Cannot divide by zero")
Enter fullscreen mode Exit fullscreen mode

Raising Exceptions

Python allows programmers to create custom exceptions using "raise".

Example

age = -5

if age < 0:
    raise ValueError("Age cannot be negative")
Enter fullscreen mode Exit fullscreen mode

Output

ValueError: Age cannot be negative
Enter fullscreen mode Exit fullscreen mode

Simple Calculator with Exception Handling

Example

try:
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))

    result = num1 / num2

    print("Result =", result)

except ValueError:
    print("Please enter valid numbers")

except ZeroDivisionError:
    print("Cannot divide by zero")
Enter fullscreen mode Exit fullscreen mode

Advantages of Exception Handling

Exception Handling makes programs:

  • More secure
  • More stable
  • Easier to maintain
  • User-friendly
  • Better at handling unexpected situations

Most real-world applications use Exception Handling extensively.


Conclusion

Exception Handling is an essential concept in Python programming because it allows programs to handle errors smoothly without crashing.

Understanding "try", "except", "else", and "finally" helps programmers build professional and reliable applications.

Practice handling different exceptions to improve your Python programming skills.

Python #PythonForBeginners #CodingJourney #LearnPython #Programming

Top comments (0)