Programming Fundamentals: by Adnan Amin Lecturer, Imsciences
Programming Fundamentals: by Adnan Amin Lecturer, Imsciences
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