0% found this document useful (0 votes)
10 views9 pages

Exception Handling - Jupyter Notebook_4f2dd58d93b90c15b6532190771836c1

The document outlines common types of errors in Python, categorizing them into Syntax Errors, Logical Errors, and Runtime Errors (Exceptions). It provides examples for each error type and explains exception handling using try-except blocks to manage errors gracefully. Additionally, it covers specific exception handling and the use of else and finally blocks for enhanced error management.

Uploaded by

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

Exception Handling - Jupyter Notebook_4f2dd58d93b90c15b6532190771836c1

The document outlines common types of errors in Python, categorizing them into Syntax Errors, Logical Errors, and Runtime Errors (Exceptions). It provides examples for each error type and explains exception handling using try-except blocks to manage errors gracefully. Additionally, it covers specific exception handling and the use of else and finally blocks for enhanced error management.

Uploaded by

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

Common Types of Errors in Python

In Python, errors can broadly be categorized into three main types: Syntax Errors, Logical
Errors and Runtime Errors (Exceptions).

1. Syntax Errors:

Syntax errors occur when the code you write does not follow the correct syntax of Python.
These errors are detected by the Python interpreter before your code runs and prevent the
program from executing.

Example:

In [1]: print("Hello, World!" # Missing closing parenthesis, causes a syntax error

Cell In[1], line 1


print("Hello, World!" # Missing closing parenthesis, causes a syntax err
or

^
SyntaxError: unexpected EOF while parsing

Explanation: This error is raised because the code is missing a closing parenthesis ) .

2. Logical Errors:

Logical errors occur when the code is syntactically correct, and it runs without any
exceptions, but it does not produce the expected result. These errors are the most
challenging to debug because they do not raise exceptions or syntax errors.

Example:

In [2]: numbers = [1, 2, 3, 4, 5]


total = sum(numbers)
average = total / len(numbers)

print("Average:", total) # Logical error: This will print the total instead o

Average: 15
Expected Output:

Average: 3.0

Actual Output:

Average: 15

Explanation: The code mistakenly prints the total instead of the average , which is a
logical error.

3. Runtime Errors (Exceptions):

Runtime errors, also known as exceptions, occur during the execution of the program. These
errors are caused by issues like invalid user input, or problems with external resources like files
or network connections. Runtime errors will halt the program unless they are properly handled.

Common Types of Exceptions:

TypeError: Occurs when an operation is performed on an inappropriate object type.

ValueError: Raised when a function receives an argument of correct type but with an
invalid value.

NameError: Raised when a local or global name is not found.

IndexError: Occurs when you try to access an index that doesn't exist in a list or other
sequence.

ZeroDivisionError: Raised when you try to divide by zero.

FileNotFoundError: Raised when a file or directory is requested but cannot be found.

Examples of Runtime Errors:

1. ZeroDivisionError:
In [3]: # Division by zero
1 / 0

---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[3], line 2
1 # Division by zero
----> 2 1 / 0

ZeroDivisionError: division by zero

ZeroDivisionError occurs when you try to divide by zero.

2. NameError:

In [4]: # Using a variable that is not defined


y = a + 5

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[4], line 2
1 # Using a variable that is not defined
----> 2 y = a + 5

NameError: name 'a' is not defined

NameError -- in this case, it means that you tried to use the variable a when it was not
defined.

3. IndexError:

In [5]: # Accessing an index that doesn't exist in a list


a = [1, 2, 3]
print(a[10]) # List has only 3 elements, so valid indices are 0, 1, 2

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[5], line 3
1 # Accessing an index that doesn't exist in a list
2 a = [1, 2, 3]
----> 3 print(a[10])

IndexError: list index out of range

IndexError -- in this case, it occured because you tried to access data from a list using an
index that does not exist for this list.
4. TypeError:

In [6]: # Trying to perform an operation on incompatible types


"hello" / "h" # You can't divide strings

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[6], line 2
1 # Trying to perform an operation on incompatible types
----> 2 "hello" / "h"

TypeError: unsupported operand type(s) for /: 'str' and 'str'

5. ValueError:

In [7]: # Input function expects an integer but receives a non-integer


a = int(input("Enter a number: ")) # Inputting a non-numeric value
print(f"Square root of {a} is {a**(1/2)}")

Enter a number: w

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[7], line 2
1 # Input function expects an integer but receives a non-integer
----> 2 a = int(input("Enter a number: ")) # Inputting a non-numeric value
3 print(f"Square root of {a} is {a**(1/2)}")

ValueError: invalid literal for int() with base 10: 'w'

Example Input:

Enter a number: w

Error Output:

ValueError: invalid literal for int() with base 10: 'w'

Explanation: The program expects a number but the user entered a letter, causing a
ValueError .

There are many more exceptions that are built into Python, here is a list of them
[https://docs.python.org/3/library/exceptions.html]
(https://docs.python.org/3/library/exceptions.html%5D)
Exception Handling
Exception handling allows your program to continue executing even when an error occurs,
instead of halting completely.

Try Except

The try-except block allows you to attempt executing code that might raise an exception. If
an exception occurs, the code inside the except block is executed. This way, your program
won't crash and can continue running.

Python tries to execute the code in the try block. In this case if there is any exception
raised by the code in the try block, it will be caught and the code block in the except
block will be executed. After that, the code that comes after the try except will be executed.

General Structure:

# Code before try-except

try:
# Code that might raise an exception
except:
# Code to handle the exception

# Code that will execute regardless of the exception

Try Except Example

This example shows how to handle potential errors that may arise when a user enters invalid
input, such as a string instead of a number, or attempts to divide by zero. The except block is
used to capture these exceptions and provide appropriate error messages to the user,
preventing the program from crashing.
In [8]: # Ask the user to input a number
try:
number = int(input("Enter a number to divide 100: "))
result = 100 / number
print(f"Result: {result}")
except:
print("There was an error")

Enter a number to divide 100: 0


There was an error

The except block catches any exceptions that might be raised during the code execution.
In this case, it catches a generic Exception to handle any potential errors.
If an exception occurs, the print("There was an error") statement is executed, providing a
general error message to the user.
If no exceptions occur, the result is printed using an f-string.

Handling Specific Exceptions

You can catch specific exceptions and handle them differently. This allows you to respond
appropriately based on the type of error.

Example of Catching Specific Exceptions:

In [9]: # Ask the user to input a number


try:
number = int(input("Enter a number to divide 100: "))
result = 100 / number
print(f"Result: {result}")
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Invalid input! Please enter a valid number.")

Enter a number to divide 100: ten


Invalid input! Please enter a valid number.

How it works:

1. Try Block: The code inside the try block asks the user for a number and attempts to
divide 100 by that number.
2. Except Blocks:

The first except block catches a ZeroDivisionError (if the user enters 0).
The second except block catches a ValueError (if the user enters something that
can't be converted to a number, like a string).

3. Output: Based on the input, the program either displays the result of the division or an
appropriate error message.

Try-Except-Else Block
The else block can be used with try-except to execute code only if no exception occurs
in the try block.

Example

In [10]: # Ask the user to input a number


try:
number = int(input("Enter a number to divide 100: "))
result = 100 / number
print(f"Result: {result}")
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Invalid input! Please enter a valid number.")
except:
print("Something went wrong.")
else:
# This block will only run if no exceptions are raised
print(f"Success! The result is: {result}")

Enter a number to divide 100: 10


Result: 10.0
Success! The result is: 10.0

The else block will only execute if no exceptions are raised in the try block. This means
that if the user enters a valid number and no errors occur, the result of the division will be
printed in the else block.

Try-Except-Finally Block
The finally block ensures that certain code runs no matter what happens, whether an
exception is raised or not. This is useful for important final steps that must happen regardless of
errors.
E l
In [11]: # Ask the user to input a number
try:
number = int(input("Enter a number to divide 100: "))
result = 100 / number
print(f"Result: {result}")
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Invalid input! Please enter a valid number.")
except:
print("Something went wrong.")
else:
# This block will only run if no exceptions are raised
print(f"Success! The result is: {result}")
finally:
# This block will always run, regardless of exceptions
print("Thank you for using the division program.")

Enter a number to divide 100: 0


You can't divide by zero!
Thank you for using the division program.

Explanation:

1. The code inside the try block is executed first.


2. If an exception occurs, such as dividing by zero ( ZeroDivisionError ), an invalid input
( ValueError ), or any other error, the corresponding except block will execute.
3. If no exception is raised, the else block runs and prints the successful result.
4. No matter what happens, whether the try block succeeds or any except block runs,
the finally block will always execute.

Summary of Exception Handling Constructs:


try: Code that might raise an exception.

except: Code to handle the exception.

else: Code that runs if no exception occurs in the try block.

finally: Code that runs regardless of whether an exception occurred, often used for
cleanup.

By mastering exception handling, you can make your programs more robust and handle errors
gracefully.

You might also like