Exception Handling - Jupyter Notebook_4f2dd58d93b90c15b6532190771836c1
Exception Handling - Jupyter Notebook_4f2dd58d93b90c15b6532190771836c1
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:
^
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:
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.
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.
ValueError: Raised when a function receives an argument of correct type but with an
invalid value.
IndexError: Occurs when you try to access an index that doesn't exist in a list or other
sequence.
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
2. NameError:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[4], line 2
1 # Using a variable that is not defined
----> 2 y = a + 5
NameError -- in this case, it means that you tried to use the variable a when it was not
defined.
3. IndexError:
---------------------------------------------------------------------------
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 -- 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:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[6], line 2
1 # Trying to perform an operation on incompatible types
----> 2 "hello" / "h"
5. ValueError:
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)}")
Example Input:
Enter a number: w
Error Output:
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:
try:
# Code that might raise an exception
except:
# Code to handle the exception
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")
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.
You can catch specific exceptions and handle them differently. This allows you to respond
appropriately based on the type of error.
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
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.")
Explanation:
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.