Python Try Except Example | Exception Handling in Python
Python Try Except Example | Exception Handling in Python is today’s topic. An exception is the error that happens during the execution of the program. When that error occurs, Python generates an exception that can be handled, which avoids your program to crash. Exceptions are a convenient way for handling errors and special conditions in the program. If you think that you have a code which can produce an error, you should use exception handling mechanism.
What are exceptions in Python?
Python has many built-in exceptions which force your program to output an error when something in it goes wrong. When these exceptions occur in the program, it causes the current process to stop and passes it to a calling process until it is appropriately handled. If not handled then our python program will crash.
Python Try Except Example
The try block lets you test the block of code for possible errors. In Python programming language, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause, and the code that handles the exception is written in except clause.
The except block lets you handle an error.
The finally block lets you execute a code, regardless of the result of the try-except blocks.
When an error occurs, or exception, Python stops executing the program and generate an error message.
Let us see a simple example.
# app.py try: print(k) except: print('One error has been thrown')
In the above code, we have not defined k variable so, the try block raises an error and the except block will be executed, and we see the output in the console.
Now, if we do not write the try-except block, then python program will crash and raise an error. See the following example.
# app.py print(k)
Exception Handling in Python
If we need to use exception handling in Python, we first need to have a catch-all except clause. The words ‘try’ and ‘except’ are Python keywords and are used to catch exceptions.
The syntax is following.
try: some statements here except: exception handling code here
See the following example.
# app.py try: print(21/0) except ZeroDivisionError: print ('You can\'t divide anything by zero, Exception Found')
So, here the try block raises an exception and except block catch that exception and run the code of except block which is to print the message in the console.
try-except else clause in Python
The else clause in the try-except statement must follow all the except clauses, and it is useful for the code that must be executed if the try clause does not raise an exception.
try: operation_that_can_throw_ioerror() except IOError: handle_the_exception_somehow() else: # we don't want to catch the IOError if it's raised another_operation_that_can_throw_ioerror() finally: something_we_always_need_to_do()
try-finally clause in Python
If the finally block specified, it will be implemented regardless if the try block raises an error or not.
# app.py try: print(21/0) except ZeroDivisionError: print ('You can\'t divide anything by zero, Exception Found') finally: print('finally block is executed')
Exception Errors Examples
The following are some predefined exceptions by Python.
IOError If the file cannot be opened. ImportError If python cannot find the module ValueError Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value KeyboardInterrupt Raised when the user hits the interrupt key (normally Control-C or Delete) EOFError Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data
You can find more about Exception Handling on python’s official docs.
Finally, Python Try Except Example | Exception Handling in Python is over.