In this tutorial, you will learn about exception handling in python 3 with examples. Exception concept is an error that python cannot handle. Python provide other way to handle the exception so that other part of code can be executed without any disturbance. If the exception handling occur program execution takes a halt. And the next code is not executed. Exception handling is also called as the abnormal condition that occurs resulting in disturbance in flow of program. Like other languages python also provides the runtime errors through exception handling method In python error can be syntax error or an exception error. When you think if you have error in code then we can use exception handling. Exception handling is useful for controlling errors in areas like loop; file handling, database communication and so on.
Syntax:-
try:
do operations here
except:
if there is exception1,then execute this block.
except exception2:
Example:-
try:
print(x)
except:
print("An exception occurred")
O/p:-
An exception has occurred
The try block raise an error, the except block will be executed.
Without the try block, the program will crash and raise an error.
Using the try and except you can avoid many problems that could arise from code.
The list of common exceptions that can be thrown from python program is given below.
The python provides facility not to specify exception with except statement.
We can declare multiple exception in except statement since try block may contain statements which trough different type of exception.
The statements that don’t throw exception should be placed inside the else block.
Also can use else statement with try-except statement in which we can place code which will be executed in scenario if no exception occurs.
The error handling is done through the use of exception that caught in true block and handled in except blocks. If error is occurred try block code execution is stopped and is transferred to except block.
Error occurs at specific time and that are of specific type.
The above errors are explained as follows:-
A compile time error occurs when you ask python to run application.
Before it run application it must interpret code and put it into form that computer can understand.
Computer can understand machine code that specific to processor and architecture.
The compile time error are easiest to spot and fix because the application can’t run with compile time error in place.
A runtime error occurs after python compiles the code you write and computer begins to execute it.
Runtime errors are different and are harder to find others, as you know that you have runtime error when application suddenly stops running and display exception dialog box.