-
Exceptions versus Syntax Errors
Syntax errors occur when the parser detects an incorrect statement.
Exception errors occurs whenever syntactically correct Python code results in an error.
-
Raising an Exception
We can use
raise
to throw an exception if a condition occurs.if x > 5: raise Exception (f"x should not exceed 5")
-
The
AssertionError
ExceptionInstead of waiting for a program to crash midway, you can also start by making an assertion in Python.
assert ("linux" in sys.platform), "This code runs on Linux Only."
-
The
try
andexcept
Block: Handling ExceptionsThe
try
andexcept
block in Python is used to catch and handle exceptions.Python executes code following the
try
statement as a “normal” part of the program.The code that follows the
except
statement is the program’s response to any exceptions in the precedingtry
clause.In the Python docs, you can see that there are a lot of built-in exceptions that you can use here.
try: with open('file.log') as file: read_data = file.read() except FileNotFoundError as fnf_error: print(fnf_error)
-
The
else
ClauseUsing the
else
statement, you can instruct a program to execute a certain block of code only in the absence of exceptions.try: linux_interaction() except AssetionError as error: print(error) else: print("Executing the else clause.")
-
Cleaning up after using
finally
Imagine that you always had to implement some sort of action to clean up after executing your code。
Python enables you to do so using the
finally
clause. -
Summing Up
raise
allows you to throw an exception at any timeassert
enables you to verify if a certain condition is met and throw an exception if it isn’t- In the
try
clause, all statements are executed until an exception is encountered; except
is used to catch and handle the exceptions that are encountered in thetry
clause;else
lets you code sections that should run only when no exceptins are encountered in thetry
clause;finally
enables you to execute sections of code that should always run, with or without any previously encountered exceptions;
-
References
再看Exception in Python
猜你喜欢
转载自blog.csdn.net/The_Time_Runner/article/details/115261430
今日推荐
周排行