Python Loop to Play Again in Try Catch
The try except statement can handle exceptions. Exceptions may happen when y'all run a program.
Exceptions are errors that happen during execution of the plan. Python won't tell you lot well-nigh errors similar syntax errors (grammar faults), instead it will abruptly stop.
An abrupt get out is bad for both the end user and developer.
Instead of an emergency halt, you tin can use a attempt except argument to properly deal with the trouble. An emergency halt volition happen if yous do not properly handle exceptions.
Related grade: Complete Python Programming Course & Exercises
What are exceptions in Python?
Python has built-in exceptions which tin output an error. If an error occurs while running the program, information technology's called an exception.
If an exception occurs, the type of exception is shown. Exceptions needs to be dealt with or the program will crash. To handle exceptions, the try-catch
cake is used.
Some exceptions you may have seen before are FileNotFoundError
, ZeroDivisionError
or ImportError
but there are many more than.
All exceptions in Python inherit from the grade BaseException. If you open the Python interactive shell and type the following argument information technology will list all built-in exceptions:
The thought of the endeavor-except clause is to handle exceptions (errors at runtime). The syntax of the try-except block is:
1 | try: |
The thought of the try-except cake is this:
-
effort: the code with the exception(southward) to take hold of. If an exception is raised, it jumps directly into the except block.
-
except: this code is only executed if an exception occured in the effort block. The except cake is required with a try block, even if information technology contains only the pass argument.
It may be combined with the else and finally keywords.
-
else: Lawmaking in the else block is but executed if no exceptions were raised in the effort block.
-
finally: The code in the finally cake is always executed, regardless of if a an exception was raised or non.
Catching Exceptions in Python
The attempt-except block tin handle exceptions. This prevents precipitous exits of the plan on mistake. In the instance below we purposely raise an exception.
one | endeavour: |
After the except block, the program continues. Without a try-except block, the final line wouldn't be reached as the program would crash.
$ python3 case.pyDivided by nothing
Should reach hither
In the above case we take hold of the specific exception ZeroDivisionError. You can handle any exception like this:
ane | endeavour: |
You can write different logic for each blazon of exception that happens:
1 | try: |
Related form: Consummate Python Programming Class & Exercises
effort-except
Lets take practice a real world example of the try-except block.
The plan asks for numeric user input. Instead the user types characters in the input box. The program normally would crash. Simply with a try-except cake it can be handled properly.
The effort except statement prevents the program from crashing and properly deals with it.
1 | try: |
Entering invalid input, makes the program continue normally:
The endeavour except statement tin be extended with the finally keyword, this will exist executed if no exception is thrown:
one | finally: |
The program continues execution if no exception has been thrown.
In that location are unlike kinds of exceptions: ZeroDivisionError, NameError, TypeError and and then on. Sometimes modules define their own exceptions.
The try-except block works for office calls too:
1 | def fail (): |
This outputs:
$ python3 example.pyException occured
Programme continues
If you are a beginner, and so I highly recommend this book.
try finally
A try-except block can have the finally clause (optionally). The finally clause is always executed.
So the general idea is:
1 | try: |
For example: if you open a file you'll want to close information technology, you can exercise so in the finally clause.
one | try: |
try else
The else clause is executed if and merely if no exception is raised. This is different from the finally clause that'south ever executed.
one | effort: |
Output:
No exception occured
Nosotros ever do this
You can catch many types of exceptions this way, where the else clause is executed only if no exception happens.
1 | effort: |
Raise Exception
Exceptions are raised when an error occurs. But in Python yous tin can also force an exception to occur with the keyword raise
.
Whatever type of exception can exist raised:
1 | raise MemoryError("Out of memory") |
1 | raise ValueError("Wrong value") |
Related grade: Consummate Python Programming Course & Exercises
Built-in exceptions
A list of Python'due south Born Exceptions is shown below. This list shows the Exception and why it is thrown (raised).Exception | Cause of Error |
---|---|
AssertionError | if assert statement fails. |
AttributeError | if attribute assignment or reference fails. |
EOFError | if the input() functions hits stop-of-file condition. |
FloatingPointError | if a floating point operation fails. |
GeneratorExit | Raise if a generator's shut() method is chosen. |
ImportError | if the imported module is non found. |
IndexError | if alphabetize of a sequence is out of range. |
KeyError | if a central is non found in a dictionary. |
KeyboardInterrupt | if the user hits interrupt key (Ctrl+c or delete). |
MemoryError | if an operation runs out of memory. |
NameError | if a variable is not establish in local or global scope. |
NotImplementedError | by abstract methods. |
OSError | if system operation causes system related error. |
OverflowError | if result of an arithmetic operation is too large to be represented. |
ReferenceError | if a weak reference proxy is used to admission a garbage nerveless referent. |
RuntimeError | if an error does not fall under whatsoever other category. |
StopIteration | by adjacent() function to indicate that there is no farther item to be returned by iterator. |
SyntaxError | by parser if syntax error is encountered. |
IndentationError | if there is incorrect indentation. |
TabError | if indentation consists of inconsistent tabs and spaces. |
SystemError | if interpreter detects internal error. |
SystemExit | past sys.exit() function. |
TypeError | if a role or operation is applied to an object of incorrect type. |
UnboundLocalError | if a reference is made to a local variable in a role or method, but no value has been bound to that variable. |
UnicodeError | if a Unicode-related encoding or decoding error occurs. |
UnicodeEncodeError | if a Unicode-related error occurs during encoding. |
UnicodeDecodeError | if a Unicode-related error occurs during decoding. |
UnicodeTranslateError | if a Unicode-related error occurs during translating. |
ValueError | if a part gets argument of right type but improper value. |
ZeroDivisionError | if second operand of division or modulo operation is zero. |
User-divers Exceptions
Python has many standard types of exceptions, but they may not always serve your purpose.
Your program can have your own type of exceptions.
To create a user-defined exception, you have to create a grade that inherits from Exception.
ane | form LunchError (Exception): |
You fabricated a user-divers exception named LunchError in the higher up lawmaking. Y'all can raise this new exception if an error occurs.
Outputs your custom fault:
$ python3 example.py
Traceback (most recent telephone call terminal):
File "instance.py", line 5, in
raise LunchError("Programmer went to luncheon")
principal.LunchError: Programmer went to luncheon
Your plan can have many user-defined exceptions. The program beneath throws exceptions based on a new projects money:
1 | course NoMoneyException (Exception): |
Here are some sample runs:
$ python3 example.py
Enter a remainder: 500
Traceback (well-nigh recent call final):
File "case.py", line 10, in
heighten NoMoneyException
main.NoMoneyException
$ python3 instance.py
$ python3 example.py
Enter a balance: 100000
Traceback (near recent phone call final):
File "example.py", line 12, in
raise OutOfBudget
main.OutOfBudget
It is a good practice to put all user-defined exceptions in a separate file (exceptions.py or errors.py). This is common do in standard modules besides.
If you are a beginner, then I highly recommend this book.
Exercises
- Tin try-except exist used to catch invalid keyboard input?
- Tin effort-except grab the error if a file tin can't be opened?
- When would yous non use try-except?
Download examples
Source: https://pythonbasics.org/try-except/
0 Response to "Python Loop to Play Again in Try Catch"
Post a Comment