EXCEPTION :
Even when Program is syntactically correct , it may still cause an error when executed. These errors occurs during run-time , known as EXCEPTION .An exception is an event ,which occur during the execution of a program and disturbs the standard flow of execution. when a compiler runs into a situation which cannot handle , it raises an exception .
Python have different types of errors.
Compile type Error (Syntax Error):
Syntax error occurs when users Violate rules of Python language and these errors are very common types of errors while learning a new language .
Logical Error : This type of error usually occurs when the program runs , but we got the wrong output. Logical errors may occur due to wrong algorithms or logic to solve a particular problem.
Run time error : Name itself suggests that this error occurs while running a program, the reason behind it is " Wrong input from user " .
Basically the first two types of errors are easy to deal with , we can find them and correct them. but when it comes to run-time error ,it's not in our hand , but as a good programmer we should be able to deal with it .Python provides some special syntax and keywords to deal with Run-time errors (exceptions).
Example :
Program to illustrate use of try ,exception and finally keywords in Exception handling :
In the above program we had to use try , except and finally keyword .
try keyword means we are not sure whether this code will run or not so compiler please check for it if code will run without any run time error then except exception block will not get execute but if there is an run-time error then it will go to exception block ,In above program we have mention exceptions like KeyboardInterrupt ,ZeroDivisionError, ValueError but if we don't know which type of run-time error will come then we can used "except exception:". exceptions can handle every type of error .
finally block will execute irrespective whether code will run or not . This block always execute even when there is run-time error
MULTIPLE EXCEPTION IN SINGLE BLOCK :
AN except clause may name multiple exceptions, so whatever exception is raised ,out of three exception specified, the name except block will execute
EXAMPLE :
Python Raise :
Raising Exceptions intentionally is Possible in Python with the help of " raise " keyword. The syntax for raise statement is
Here, Exception is the name of an exception to be raised (TypeError) .args is optional and specifies a value for the exception argument .Default value of args is None .
Example :
In the above example there is no error .We had declared a variable and just printed it. But we have intentionally raised an exception .
List of built in Exception :
As a good programmer we should have knowledge different exceptions in Python