0% found this document useful (0 votes)
16 views

Exception Handling in Python: Mohammed Sikander

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Exception Handling in Python: Mohammed Sikander

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Exception Handling in Python

Mohammed Sikander
Python
Exceptions
Exception Handling
Try and Except
Nested try Block
Handling Multiple Exceptions in single Except Block
Raising Exception
Finally Block
User Defined Exceptions
Exception
 When writing a program, we, more often than not,
will encounter errors.
 Error caused by not following the proper structure
(syntax) of the language is called syntax error or
parsing error
 Errors can also occur at runtime and these are called
exceptions.
 They occur, for example, when a file we try to open
does not exist (FileNotFoundError), dividing a
number by zero (ZeroDivisionError)
 Whenever these type of runtime error occur, Python
creates an exception object. If not handled properly, it
prints a traceback to that error along with some
details about why that error occurred.
Exception Handling
 To handle exceptions, and to call code when
an exception occurs, we can use a
try/except statement.
 The try block contains code that might
throw an exception.
 If that exception occurs, the code in the try
block stops being executed, and the code in
the except block is executed.
 If no error occurs, the code in the except
block doesn't execute.
Nested Try Block
 A try statement can have multiple
different except blocks to handle
different exceptions.
 Multiple exceptions can also be put into a
single except block using parentheses, to
have the except block handle all of them.
Raising Exceptions
Raising Exception from Except Block
finally
 To ensure some code runs no matter
what errors occur, you can use a finally
statement.
 The finally statement is placed at the
bottom of a try/except statement.
 Code within a finally statement always
runs after execution of the code in the
try, and possibly in the except, blocks.
 Code in a finally statement even runs if
an uncaught exception occurs in one of
the preceding blocks.
Raising Exception
 Raising exception is similar to throwing
exception in C++/Java.
 You can raise exceptions by using
the raise statement
User Defined Exception

You might also like