0% found this document useful (0 votes)
16 views6 pages

Programming Fundamentals: by Adnan Amin Lecturer, Imsciences

Uploaded by

Salman Zaib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views6 pages

Programming Fundamentals: by Adnan Amin Lecturer, Imsciences

Uploaded by

Salman Zaib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Programming Fundamentals

BY
Adnan Amin
Lecturer, IMSciences
Exceptions
• An exception is a program error that causes the program to crash. Try/except
allows you to gracefully handle exceptions.
• For example:
• A number divided by zero
• It is your responsibility to write code that responds to exceptions when they are
raised and prevents the program from crashing unexpectedly.
• Technique is used is known as exception handler, and it is written using the
try/except syntax.
• Syntax:
• Try: IOError
• Statement 1
ValueError
• Statement N
• except ExceptionName:
• Statement(s)
Exception Handler
Handling Multiple exceptions
• try:
• Statement(s)
• except IOError:
• Statement(s) #An error occured trying to read the file.
• except ValueError:
• Statement(s) #Non-numeric data found in the file.
• except:
• Statement(s) #Using One except Clause to Catch All exceptions

except ValueError as err:


print(err)
The else Clause
• The try/except statement may have an optional else clause, which
appears after all the except clauses.
• General format:
• try:
• statement (s)
• except ExceptionName:
• statement (s)
• else:
• statement (s)
The statements in the else suite are executed after the
statements in the try suite, only if no exceptions were raised. If
an exception is raised, the else suite is skipped.
The finally Clause
• The try/except statement may have an optional finally clause, which
must appear after all the except clauses.
• General format:
• try:
• Statement(s)
• except ExceptionName:
• Statement(s)
• finally:
• Statement(s) The statements in the finally suite execute whether an
exception occurs or not. The purpose of the finally suite is to
perform cleanup operations, such as closing files or other
resources.

You might also like