# potential code before try catch
try:
# code to try to execute
except:
# code to execute if there is an exception
# code that will still execute if there is an exception
Errors & Exceptions
Errors
- Well,
errors
are usually big problems that come from the computer or the system. - They often make the program stop working completely.
Here are a few examples, many more exist:
ZeroDivisionError: This error arises when an attempt is made to divide a number by zero. Division by zero is undefined in mathematics, causing an arithmetic error. result = 10/0
ValueError: This error occurs when an inappropriate value is used within the code. An example of this is when trying to convert a non-numeric string to an integer: num = int("abc")
FileNotFoundError: This exception is encountered when an attempt is made to access a file that does not exist.
IndexError: An IndexError occurs when an index is used to access an element in a list that is outside the valid index range: my_list = [1, 2, 3] then use missing = my_list[5]
KeyError: The KeyError arises when an attempt is made to access a non-existent key in a dictionary.
TypeError: The TypeError occurs when an object is used in an incompatible manner. An example includes trying to concatenate a string and an integer: result = "hello" + 5
AttributeError: An AttributeError occurs when an attribute or method is accessed on an object that doesn’t possess that specific attribute or method. text ="sample" then use missing = text.some_method()
ImportError: This error is encountered when an attempt is made to import a module that is unavailable. For example: import non_existent_module
Exceptions
Exceptions are alerts when something unexpected happens while running a program.
- It could be a mistake in the code or a situation that was not planned for.
- Python can raise these alerts automatically, but we can also trigger them on purpose using the
raise
command. - The cool part is that we can prevent our program from crashing by handling exceptions.
- On the other hand,
exceptions
are more like issues we can control. - They happen because of something we did in our code and can usually be fixed, so the program keeps going.
Handling Exceptions
Python has a handy tool called try and except
that helps us manage exceptions.
Try and Except
You can use the try and except blocks to prevent your program from crashing due to exceptions.
Here’s how they work:
- The code that may result in an exception is contained in the try block.
- If an exception occurs, the code directly jumps to except block.
- In the except block, you can define how to handle the exception gracefully, like displaying an error message or taking alternative actions.
- After the except block, the program continues executing the remaining code.
- If you need to include several except statements then use else for each one
Final Block
- Code in the final block will always execute
try:
file = open("data.txt", "r")
= file.read()
data except FileNotFoundError:
print("File not found.")
finally:
file.close()
Example: General
- In this example we are trying to divide a number given by the user, save the outcome in the variable
a
, and then - we would like to print the result of the operation.
- When taking user input and dividing a number by it there are a couple of exceptions that can be raised
- For example if we divide by zero.
- Try running the following block of code with
b
as a number. - An exception will only be raised if
b
is zero.
= 1
a
try:
= int(input("Please enter a number to divide a"))
b = a/b
a print("Success a=",a)
except:
print("There was an error")
There was an error
Example: Specific Try Except
- A specific
try except
allows you to catch certain exceptions and also execute certain code depending on the exception. - This is useful if you do not want to deal with some exceptions and the execution should halt.
- It can also help you find errors in your code that you might not be aware of.
- Furthermore, it can help you differentiate responses to different exceptions.
- In this case, the code after the try except might not run depending on the error.
= 1
a
try:
= int(input("Please enter a number to divide a"))
b = a/b
a print("Success a=",a)
except ZeroDivisionError:
print("The number you provided cant divide 1 because it is 0")
except ValueError:
print("You did not provide a number")
except:
print("Something went wrong")
Something went wrong
try:
= 10
numerator = 0
denominator = numerator / denominator
result print(result)
except ZeroDivisionError:
print("Error: Denominator cannot be 0.")
Error: Denominator cannot be 0.
# using Try- except
try:
# Attempting to divide 10 by 0
= 10 / 0
result
except ZeroDivisionError:
# Handling the ZeroDivisionError and printing an error message
print("Error: Cannot divide by zero")
except NameError:
print("Error: nameerror")
# This line will be executed regardless of whether an exception occurred
print("outside of try and except block")
Error: Cannot divide by zero
outside of try and except block
Example Using Else
else
allows one to check if there was no exception when executing the try block. This is useful when we want to execute something only if there were no errors.finally
allows us to always execute something even if there is an exception or not. This is usually used to signify the end of the try except.
= 1
a
try:
= int(input("Please enter a number to divide a"))
b = a/b
a except ZeroDivisionError:
print("The number you provided cant divide 1 because it is 0")
except ValueError:
print("You did not provide a number")
except:
print("Something went wrong")
else:
print("success a=",a)
finally:
print("Processing Complete")
Something went wrong
Processing Complete
Errors vs Exceptions
Aspect | Errors | Exceptions |
---|---|---|
Origin | Errors are typically caused by the environment, hardware, or operating system. | Exceptions are usually a result of problematic code execution within the program. |
Nature | Errors are often severe and can lead to program crashes or abnormal termination. | Exceptions are generally less severe and can be caught and handled to prevent program termination. |
Handling | Errors are not usually caught or handled by the program itself. | Exceptions can be caught using try-except blocks and dealt with gracefully, allowing the program to continue execution. |
Examples | Examples include “SyntaxError” due to incorrect syntax or “NameError” when a variable is not defined. | Examples include “ZeroDivisionError” when dividing by zero, or “FileNotFoundError” when attempting to open a non-existent file. |
Categorization | Errors are not classified into categories. | Exceptions are categorized into various classes, such as “ArithmeticError,” “IOError,” ValueError,” etc., based on their nature. |