Python Programming
– Exceptions
Networking for Software Developer
Narendra Pershad
Agenda
• Errors
• What are exceptions?
• Why is it necessary?
• Examples
Errors
• Errors prevents your program must running as expected (or as you hope)
• There are basically two kinds of errors that you might get
• Syntax Errors
• Normally comes from coding mistakes
• Exceptions
• Normally come from some abnormalities in execution
Syntax Errors
• Also called parsing errors.
• It is the most common type of error.
• Especially if you are now learning the language.
• The parser tokenizes the source code and then parses according to the grammar of the language.
• The parser prints the offending line with an arrow indicating the earliest point where the error was detected.
• This is not an issue for complied languages such C++, C, java and C# where all the syntax are caught before
the executable is built.
Exception
• Exception handling is a critical practice in building robust applications.
• Whenever something abnormal happens an exception object in
generated and raised.
• If you don’t handle the exception then the program will terminate.
Full Syntax
try:
pass #statements that may cause exception
except:
pass #processed if that is an exception
else: #optional
pass #processed if that is no exception
finally: #optional
pass #guarantee to be processed even if there is no
exception
Simple Syntax
try:
file = open('test.txt', 'rb') #this can potentially raise an exception
except Exception as e: #this will catch all errors
print(f'Error {e} has occurred')
Simple Syntax
try:
file = open('test.txt', 'rb')
except ( IOError, EOFError ) as e: #this will catch only these errors
print(f'Error {e} has occurred')
Simple Syntax
try:
file = class('test.txt', 'rb')
except EOFError as e: #catching specific error
print(f'Error {e} has occurred')
except IOError as e: #this will catch only this error
print(f'Error {e} has occurred')
Raising Exception
name = input('Please enter your name: ‘)
try:
if name == 'Narendra’:
raise Exception('Narendra is evil!’) #raise an exception
else:
print(f'Hello {name}')
except Exception as e:
print(e)
Summary
• There are two kinds of errors that a user might encounter
• Syntax Errors
• Caused by the programmers not following the grammar of the language
• These are caught by the parser
• Exceptions
• Happens when the control flow is disrupted
• These are caught by the runtime if no handled by the programmer
• Exception handling is critical to writing robust code