Presentation is loading. Please wait.

Presentation is loading. Please wait.

ERRORS AND EXCEPTIONS Errors:

Similar presentations


Presentation on theme: "ERRORS AND EXCEPTIONS Errors:"— Presentation transcript:

1 ERRORS AND EXCEPTIONS Errors:
There are many type of errors that can occur in a program. The error caused by writing an improper syntax is termed as syntax error or parsing error. These errors are also called as compile time errors. Exceptions: Errors can also occur at runtime and these runtime errors are known as exceptions. Examples: FileNot found,Import Error, ZeroDivisionError, ect. The user must write a piece of code that can handle the exceptions. If the program is not able to handle the error, it prints a trace back to tha terror along with the details of why the error has occurred.

2 Built-in exceptions in python
Sl.no EXCEPTION Cause of error 1 Import Error Raised when the imported module does not exist. Eg: import mat ImportError: No module named mat 2 IndexError Raised when an index of a sequence is out of range or not found list1=[10,20,30] print (list[5]) IndexError: list index out of range 3 KeyError Raised when a key does not exist in a dictionary. Eg:Dict1={1:’a’,2:’b’} print (Dict1[4]) KeyError: Key not Found 4. Keyboard Interrupt Raised when a user hits interrupt key(ctrl+c)

3 5 Name error Raised when a variable is found in local or global scope. Eg:Dict1={1:’a’,2:’b’} del Dict1 print (Dict1) NameError: name ‘Dict1’ is not defined 6 IOError Raised when input file does not exist or we do not have permission to access the file. Eg: file=open(“C:/python27/test.txt”,”w”) file.write(“Hi”) IOError: File cannot be located 7 Stop Iteration Raised when there is no next item to be iterated by iterator. 8 Syntax error Raised when a syntax error occurs Eg:while True print('Hello world') SyntaxError: invalid syntax 9. Indentation Error Raised when there is incorrect indentation Eg:def a(): ... print “Hi" ... print “Hello“ IndentationError: unexpected indent 10 System error Raised when an internal error occurs.

4 11 Tab error Raised when indentation is composed of inconsistent tabs and spaces Eg: while True : _ _ _print('Hello world') TabError:Inconsistent Indentation 12 Type error Raised when a function or operation is applied to an object of incorrect type. '2' + 2 TypeError: Can't convert 'int' object to str implicitly 13 Zero division Error Raised when a number is divided by zero. 10 * (1/0) ZeroDivisionError: division by zero 14 Value Error Raised when a function is passed with an argument of correct type but improper value. x,y=1,2,3,4 Value error: too many values to unpack 15. Run time error Raised when error does not fall into any other category.

5 Handling Exceptions Python provides a very important feature called as EXCEPTION HANDLING for handling any unexpected error in our python programs, and it also adds debug capabilities to them. Whenever an exception occurs, the program stops the current process and passes it to the calling process until it is handled. If there is no piece of code in our program to handle the exception , then the program will crash. For eg, assume that a function X calls function Y, which in turn calls function Z and an exception occurs in Z. If this exception is not handled in Z itself, then the exception is passed to Y and then to X. If this exception is not handled, then an error message will be displayed and our program will suddenly stop.

6 Methods to handle exception:
try… except except with No Exception except with Multiple Exceptions try… finally

7 1.try…except An operation in the program than can cause the exception is placed in the try clause while the block of code that handles the exception is placed in the except clause. The block of code for handling the exception is written by the user and it is for him to decide which operation he wants to perform after the exception has been identified. A try block can have multiple except claused associated with it. else block will execute only when the statements in the try block do not raise any exception.

8 the operation which can cause exception here, …………………………………………………
EXAMPLE >>>try: … file=open(“C:/python27/test.txt”,”w”) … file.write(“HELLO”) … except IOError: … print(“Error: cannot find file or write”) … except ZerodivisionError: … print(“Error: check calculation”) … else: … print(“content written successfully”) >>>file.close() NOTE: If the file is not found or we do not have permission to write in this file, an exception is raised. This exception is handled by the except block and we will get the output as, Error: cannot find file or write On the other hand, if data is written successfully, Else block is executed and we will get output as, content written successfully Syntax: try: the operation which can cause exception here, ………………………………………………… except Exception1: if there is exception 1, execute this. except Exception2: if there is exception 2, execute this. else: if no exception occurs, execute this.

9 2.Except with No Exception
We can also write try-except clause with no exception. All types of exception that occur are caught by the try-except statement. However, because it caches all exceptions the programmer cannot identify the root cause of a problem that may occur. Hence this type of programming approach is not considered good.

10 Syntax: try: the statements that can cause exceptions ……………………… except : if exception occurs, execute this. else: if no exception occurs, execute this. Example: >>>while True: try: … a=int(input()) … div=10/a … except: … print(“Error”) … print(“Enter valid i/p”) … else: … print (“result=”,div) Output for the program in different scenarios: C Error Enter valid i/p 0 5 result=2.5

11 3.except with Multiple Exceptions In Python, we can also use the same except statement for handling multiple exceptions in one statement Example: try: … div=10/0 … print(div) except(TypeError,ZeroDivisionError, ValueError): … PASS else: try: the operation which can cause exception here, ……………………… except (Exception1, Exception2,….,Exception N): if any of the exception occurs, from the above list, execute this. else: if no exception occurs, execute this.

12 We cannot use else clause along with a finally clause
4.try…finally The try statement in Python has an optional finally clause that can be associated with it. The statements written in finally clause will always be executed by the interpreter, whether the try statement raises an exception or not. With the try clause , we can either use except or finally, but not both. We cannot use else clause along with a finally clause

13 SYNTAX: try: the operation which can cause exception here, …………………….. This may be skipped due to exception finally: This will always be executed Example: >>>try: … file=open(“testfile”,”w”) … file.write(“Hello”) … finally: … print(“closing file”) … file.close() … except IOError: … print(“Error Occured”)

14 In the given example, when an exception is raised by the statements of try block, the execution is immediately passed to the finally block. After all the statements inside finally block are executed, the exception is raised again and is handled by the except block that is associated with try block.


Download ppt "ERRORS AND EXCEPTIONS Errors:"

Similar presentations


Ads by Google