0% found this document useful (0 votes)
13 views4 pages

Python Errors and Exceptions

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views4 pages

Python Errors and Exceptions

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 4

Errors and Exceptions in Python

Errors and Exceptions in Python

In Python, errors and exceptions are critical aspects of handling unexpected events and conditions

that occur during the execution of a program. Understanding how to manage these effectively can

help make your code more robust and easier to debug.

Types of Errors

1. Syntax Errors:

- Occur when the parser detects an incorrect statement.

- Example:

print("Hello, world!"

This will result in a SyntaxError because of the missing closing parenthesis.

2. Runtime Errors:

- Occur during execution and are often called exceptions.

- Example:

print(1 / 0)

This will result in a ZeroDivisionError because you cannot divide a number by zero.

Common Built-in Exceptions

1. ValueError:

- Raised when a function receives an argument of the right type but inappropriate value.
Errors and Exceptions in Python

- Example:

int("abc") # Raises ValueError

2. TypeError:

- Raised when an operation or function is applied to an object of inappropriate type.

- Example:

"2" + 2 # Raises TypeError

3. IndexError:

- Raised when a sequence subscript is out of range.

- Example:

my_list = [1, 2, 3]

my_list[5] # Raises IndexError

4. KeyError:

- Raised when a dictionary key is not found.

- Example:

my_dict = {"a": 1}

my_dict["b"] # Raises KeyError

5. FileNotFoundError:

- Raised when a file or directory is requested but doesn't exist.

- Example:

open("non_existent_file.txt") # Raises FileNotFoundError


Errors and Exceptions in Python

Handling Exceptions

Python provides a way to handle exceptions using try, except, else, and finally blocks.

- try: The block of code to be tested for errors.

- except: The block of code to be executed if an error occurs in the try block.

- else: The block of code to be executed if no error occurs.

- finally: The block of code to be executed regardless of the outcome.

Example:

try:

# Code that might raise an exception

result = 10 / 0

except ZeroDivisionError:

# Code to execute if a ZeroDivisionError occurs

print("You cannot divide by zero!")

else:

# Code to execute if no exception occurs

print("Division was successful")

finally:

# Code to execute regardless of what happens

print("This will always be executed")

Custom Exceptions
Errors and Exceptions in Python

You can also define your own exceptions by creating a new class derived from the built-in Exception

class.

Example:

class MyCustomError(Exception):

pass

def do_something():

raise MyCustomError("Something went wrong")

try:

do_something()

except MyCustomError as e:

print(e)

Summary

- Syntax Errors are detected during parsing and prevent the program from running.

- Runtime Errors (exceptions) occur during program execution.

- Common exceptions include ValueError, TypeError, IndexError, KeyError, and FileNotFoundError.

- Exceptions are handled using try, except, else, and finally blocks.

- Custom exceptions can be created by inheriting from the Exception class.

Understanding and using these concepts will help you write more reliable and maintainable Python

code.

You might also like