19
loading...
This website collects cookies to deliver better user experience
finally
statementelse
statementtry:
# Do something that may raise exception
except ExceptionName:
# Handle the exception
try
block, we generally put the code that may raise an exception. In the except
block, we handle the exception raised in the try block. The code in the except
block runs only if the name of the exception matches the ExceptionName. For example, if we try to open a file that doesn't happen to exist in the system, we get a FileNotFoundError.with open("test.txt") as f:
data = f.readlines()
print(data)
$ py test.py
Traceback (most recent call last):
File "C:\Users\ashut\Desktop\Test\hello\test.py", line 1, in <module>
with open("test.txt") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
try:
with open("test.txt") as f:
data = f.readlines()
print(data)
except FileNotFoundError:
print("File could not be found!!")
$ py test.py
File could not be found!!
except
block without specifying any exception name. It is called bare exception , but it's not recommended. The reason it is bad practice to create a bare except is that you don’t know what types of exceptions you are catching, nor exactly where they are occurring. This can make figuring out what you did wrong more difficult. If you narrow the exception types down to the ones you know how to deal with, then the unexpected ones will make your application crash with a useful message. At that point, you can decide if you want to catch that other exception or not.try:
with open("test.txt") as f:
data = f.readlines()
print(data)
except:
print("Something went wrong!")
$ py test.py
Something went wrong!
try:
with open("test.txt") as f:
data = f.readlines()
print(data)
from fastapi import FastAPI
except FileNotFoundError:
print("File could not be found!!")
except ImportError:
print("Library not installed!!")
except FileNotFoundError
block and we get an error message saying File could not be found!! If the file is found and fastapi
is not installed, the except ImportError
block handles the next exception and outputs _Library not installed!! _This exception handler will catch only two types of exceptions: FileNotFoundError and ImportError. If another type of exception occurs, this handler won’t catch it and your code will stop.try:
with open("test.txt") as f:
data = f.readlines()
print(data)
from fastapi import FastAPI
except (FileNotFoundError, ImportError):
print("Something went wrong!!")
raise
statement to throw exceptions.>>> raise FileNotFoundError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError
>>> raise FileNotFoundError('I am a custom message')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: I am a custom message
>>> class UserError(Exception):
... pass
...
>>> raise UserError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.UserError
>>> raise UserError("I am a custom error")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.UserError: I am a custom error
UserError
which inherits from the Exception
class. This new exception, like other exceptions, can be raised using the raise
statement with an optional error message.class ValueTooSmallError(Exception):
"""Raised when the guessed value is too small"""
pass
class ValueTooLargeError(Exception):
"""Raised when the guessed value is too large"""
pass
# guess this number
number = 10
# user guesses a number until he/she gets it right
while True:
try:
user_guess = int(input("Enter a number: "))
if user_guess < number:
raise ValueTooSmallError
elif user_guess > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("Too low, try again!")
except ValueTooLargeError:
print("Too large, try again!")
print("Congratulations! You guessed it right.")
$ py test.py
Enter a number: 17
Too large, try again!
Enter a number: 3
Too low, try again!
Enter a number: 10
Congratulations! You guessed it right.
ValueTooSmallError
and ValueTooLargeError
that inherits the built-in Exception class. class AgeNotValidError(Exception):
"""Exception raised for errors in the age.
Attributes:
age -- input age that caused the error
message -- explanation of the error
"""
def __init__ (self, age, message="Your age must be equal to or greater than 18 years"):
self.age = age
self.message = message
super(). __init__ (self.message)
age = int(input("Enter your age: "))
if not age >= 18:
raise AgeNotValidError(age)
$ py test.py
Enter your age: 16
Traceback (most recent call last):
File "C:\Users\ashut\Desktop\Test\hello\test.py", line 17, in <module>
raise AgeNotValidError(age)
__main__.AgeNotValidError: Your age must be equal to or greater than 18 years
Exception
class to accept our own custom arguments age
and message
. Then, the constructor of the parent Exception
class is called manually with the self.message
argument using super()
.self.age
attribute is defined to be used later. class AgeNotValidError(Exception):
"""Exception raised for errors in the age.
Attributes:
age -- input age that caused the error
message -- explanation of the error
"""
def __init__ (self, age, message="Your age must be equal to or greater than 18 years"):
self.age = age
self.message = message
super(). __init__ (self.message)
age = int(input("Enter your age: "))
if not age >= 18:
raise AgeNotValidError(age, message=f"Your age is {age} but should be greater than or equal to 18.")
$ py test.py
Enter your age: 13
Traceback (most recent call last):
File "C:\Users\ashut\Desktop\Test\hello\test.py", line 17, in <module>
raise AgeNotValidError(age, message=f"Your age is {age} but should be greater than or equal to 18.")
__main__.AgeNotValidError: Your age is 13 but should be greater than or equal to 18.
__str__
method of the Exception
class is then used to display the corresponding message when AgeNotValidError
is raised.__str__
method itself by overriding it.class AgeNotValidError(Exception):
"""Exception raised for errors in the age.
Attributes:
age -- input age that caused the error
message -- explanation of the error
"""
def __init__ (self, age, message="Your age must be equal to or greater than 18 years"):
self.age = age
self.message = message
super(). __init__ (self.message)
def __str__ (self):
return f"{self.message}\nGiven Age: {self.age}"
age = int(input("Enter your age: "))
if not age >= 18:
raise AgeNotValidError(age)
$ py test.py
Enter your age: 14
Traceback (most recent call last):
File "C:\Users\ashut\Desktop\Test\hello\test.py", line 20, in <module>
raise AgeNotValidError(age)
__main__.AgeNotValidError: Your age must be equal to or greater than 18 years
Given Age: 14
try:
f = open("hello.txt", "w")
import fastapi
except ImportError:
print("An ImportError occurred")
finally:
f.close()
print("Closed the file")
$ py test.py
An ImportError occurred
Closed the file
try:
f = open("hello.txt", "w")
import fastapi
finally:
f.close()
print("Closed the file")
$ py test.py
Closed the file
Traceback (most recent call last):
File "C:\Users\ashut\Desktop\Test\hello\test.py", line 3, in <module>
import fastapi
ModuleNotFoundError: No module named 'fastapi'
try:
print("I am try block")
except ImportError:
print("I am except block")
else:
print("I am else block")
$ py test.py
I am try block
I am else block
try:
raise ImportError
print("I am try block")
except ImportError:
print("I am except block")
else:
print("I am else block")
$ py test.py
I am except block