0% found this document useful (0 votes)
0 views8 pages

Python Exception Handling

This tutorial provides a comprehensive guide to Python exception handling, covering try-except blocks, handling multiple exceptions, and using else and finally blocks. It emphasizes the importance of exception handling in preventing program crashes, providing meaningful error messages, and performing cleanup actions. The tutorial includes practical examples and tips for effectively managing exceptions in Python programming.

Uploaded by

daniel.tufa2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views8 pages

Python Exception Handling

This tutorial provides a comprehensive guide to Python exception handling, covering try-except blocks, handling multiple exceptions, and using else and finally blocks. It emphasizes the importance of exception handling in preventing program crashes, providing meaningful error messages, and performing cleanup actions. The tutorial includes practical examples and tips for effectively managing exceptions in Python programming.

Uploaded by

daniel.tufa2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Python Exception Handling Tutorial

This tutorial provides a comprehensive guide to Python exception handling, based on information from
W3Schools (Python Try Except). It covers the essential concepts, including try-except blocks, handling
multiple exceptions, using else and finally blocks, and raising exceptions manually. Each section includes
explanations and practical examples to help beginners understand and apply exception handling
effectively.

Introduction to Exception Handling

In Python, an exception is an error that occurs during program execution, such as trying to access an
undefined variable or dividing by zero. Without handling, these exceptions cause the program to crash
and display an error message. Exception handling allows you to catch these errors and respond
appropriately, ensuring your program continues running or fails gracefully.

Exception handling is critical for:

Preventing program crashes due to unexpected errors.

Providing meaningful error messages to users.

Performing cleanup actions, like closing files, even if an error occurs.

The Try-Except Block

The try-except block is the cornerstone of exception handling in Python. The try block contains code that
might raise an exception, while the except block defines how to handle the error.

Syntax

try:

# Code that might raise an exception

except:

# Code to handle the exception

Example

try:

print(x)
except:

print("An exception occurred")

Explanation:

If x is not defined, Python raises a NameError.

The except block catches the error and prints "An exception occurred" instead of crashing.

Try this example at W3Schools Try It Yourself.

Handling Multiple Exceptions

You can handle different types of exceptions by specifying multiple except blocks, each targeting a
specific exception type. A general except block can catch any unspecified exceptions.

Syntax

try:

# Code that might raise an exception

except ExceptionType1:

# Handle ExceptionType1

except ExceptionType2:

# Handle ExceptionType2

except:

# Handle any other exceptions

Example

try:

print(x)

except NameError:
print("Variable x is not defined")

except:

print("Something else went wrong")

Explanation:

If x is undefined, the NameError block runs, printing "Variable x is not defined."

If another type of exception occurs, the general except block handles it.

Try this example at W3Schools Try It Yourself.

Common Exception Types

Here are some common built-in exceptions in Python:

Exception Type

Description

NameError

Raised when a variable is not defined.

TypeError
Raised when an operation is applied to an inappropriate type.

ValueError

Raised when a function receives an argument of the correct type but an invalid value.

ZeroDivisionError

Raised when dividing by zero.

For a full list, see Python Built-in Exceptions Reference.

The Else Block

The else block is optional and runs only if no exceptions occur in the try block. It’s useful for code that
should execute only when the try block succeeds.

Syntax

try:

# Code that might raise an exception

except:

# Handle the exception

else:

# Code to run if no exception occurs

Example

try:

print("Hello")
except:

print("Something went wrong")

else:

print("Nothing went wrong")

Explanation:

Since print("Hello") executes without errors, the else block runs, printing "Nothing went wrong."

Try this example at W3Schools Try It Yourself.

The Finally Block

The finally block is optional and always executes, regardless of whether an exception occurred. It’s
commonly used for cleanup actions, such as closing files or releasing resources.

Syntax

try:

# Code that might raise an exception

except:

# Handle the exception

finally:

# Code that always runs

Example

try:

f = open("demofile.txt")

try:

f.write("Lorum Ipsum")
except:

print("Something went wrong when writing to the file")

finally:

f.close()

except:

print("Something went wrong when opening the file")

Explanation:

The finally block ensures the file is closed, even if an error occurs while opening or writing to it.

This prevents resource leaks, such as leaving files open.

Try this example at W3Schools Try It Yourself.

Raising Exceptions

You can manually raise exceptions using the raise keyword to enforce conditions or validate inputs. You
can raise a generic Exception or a specific exception type like TypeError.

Syntax

if condition:

raise Exception("Error message")

Example 1: Generic Exception

x = -1

if x < 0:

raise Exception("Sorry, no numbers below zero")

Explanation:
If x is negative, the program raises an exception with the message "Sorry, no numbers below zero."

Try this example at W3Schools Try It Yourself.

Example 2: Specific Exception

x = "hello"

if not isinstance(x, int):

raise TypeError("Only integers are allowed")

Explanation:

If x is not an integer, a TypeError is raised with the message "Only integers are allowed."

Try this example at W3Schools Try It Yourself.

Practical Tips

Be Specific: Catch specific exceptions (e.g., NameError, TypeError) before a general except to avoid
masking unexpected errors.

Use Finally for Cleanup: Always close resources like files or database connections in a finally block.

Raise Meaningful Exceptions: Use raise to enforce rules and provide clear error messages.

Test Your Code: Use W3Schools’ “Try It Yourself” links to experiment with the examples and see how
they work.

References

W3Schools: Python Try Except


W3Schools: Python Built-in Exceptions Reference

Conclusion

Exception handling is essential for writing robust Python programs. By using try-except blocks, you can
catch and handle errors gracefully. The else block allows you to run code when no errors occur, while
the finally block ensures cleanup actions are performed. Raising exceptions manually with raise gives
you control over error conditions. With these tools, you can build reliable and user-friendly Python
applications.

Note: This tutorial is based on information from W3Schools, specifically the Python Try Except page,
accessed on July 17, 2025.

You might also like