SoFunction
Updated on 2024-11-10

Python Example of Exception Handling Explained

I. What is an anomaly?
An exception is an event that occurs during program execution and affects the normal execution of the program.
Typically, an exception occurs when Python is unable to handle a program properly.
Exceptions are Python objects that represent an error.
When an exception occurs in a Python script we need to catch it and handle it, otherwise the program will terminate.
II. Exception handling
Catching exceptions can be done using try/except statements.
The try/except statements are used to detect errors in the try statement block so that the except statement can catch the exception information and handle it.
If you don't want to end your program when an exception occurs, just catch it in try.

Exception syntax:
Here is a simple try... .except... ...else syntax:

Copy Code The code is as follows.
try:
<statement> #run other code
except <name>:
<statement> #If 'name' exception is thrown in try section
except <name>, <data>.
<statement> #Get additional data if 'name' exception is raised
else:
<statement> #If no exception occurs

The way try works is that when a try statement is started, python marks it in the context of the current program so that you can come back to it when an exception occurs; the try clause executes first, and what happens next depends on whether or not an exception occurs during execution.

If an exception occurs while the statement following the try is executing, python jumps back to the try and executes the first exception clause that matches the exception, and the exception is handled, and control flows through the entire try statement (unless a new exception is thrown while handling the exception).
If an exception occurs in a statement following a try without a matching except clause, the exception will be handed to the upper level of the try, or to the top level of the program (which will end the program and print the default error message).
If no exception occurs while the try clause is executing, python executes the statement following the else statement (if there is an else) and then control flows through the entire try statement.

Exception Handling Example 1.
The following is a simple example that opens a file, writes content to the contents of that file, and no exception occurs:

Copy Code The code is as follows.
#!/usr/bin/python

try:
   fh = open("testfile", "w")
   ("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Written content in the file successfully"
   ()


The above program outputs the results:
Copy Code The code is as follows.
Written content in the file successfully

Exception Handling Example 2.
The following is a simple example where it opens a file, writes content in the contents of that file, but the file does not have write permissions and an exception occurs:
Copy Code The code is as follows.
#!/usr/bin/python

try:
   fh = open("testfile", "w")
   ("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Written content in the file successfully"


The above program outputs the results:
Copy Code The code is as follows.
Error: can't find file or read data

III. Use except without any exception types

You can use except without any exception type, as in the following example:

Copy Code The code is as follows.

try:
   You do your operations here;
   ......................
except:
   If there is any exception, then execute this block.
   ......................
else:
   If there is no exception then execute this block.

The above way try-except statement catches all the exceptions that occur. But this is not a good way, we can't identify the specific exception information through this program. Because it catches all the exceptions.
Using except with multiple exception types
You can also use the same except statement for multiple exception messages, as shown below:
Copy Code The code is as follows.
try:
   You do your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list,
   then execute this block.
   ......................
else:
   If there is no exception then execute this block.

V. The try-finally statement
The try-finally statement executes the final code regardless of whether an exception occurs.
Copy Code The code is as follows.
try:
<statement>.
finally:
<statement> #always executed when exiting a try
raise

Note: You can use either the except statement or the finally statement, but not both, and the else statement cannot be used in conjunction with the finally statement.

Examples of try-finally usage:

Copy Code The code is as follows.
#!/usr/bin/python

try:
   fh = open("testfile", "w")
   ("This is my test file for exception handling!!")
finally:
   print "Error: can\'t find file or read data"


If the opened file does not have writable permissions, the output is shown below:
Copy Code The code is as follows.
Error: can't find file or read data

The same example can be written in the following way:
Copy Code The code is as follows.
#!/usr/bin/python

try:
   fh = open("testfile", "w")
   try:
      ("This is my test file for exception handling!!")
   finally:
      print "Going to close the file"
      ()
except IOError:
   print "Error: can\'t find file or read data"


When an exception is thrown in a try block, the finally block code is executed immediately.
After all statements in the finally block are executed, the exception is raised again and the except block code is executed.
The content of the parameter is different from the exception.

VI. Parameters of the exception
An exception can take parameters with it, which can be used as parameters for the output exception message.
You can catch the parameters of an exception with the except statement, as shown below:

Copy Code The code is as follows.
try:
   You do your operations here;
   ......................
except ExceptionType, Argument:
   You can print value of Argument here...

The exception value received by the variable is usually included in the statement of the exception. Variables in tuple forms can receive one or more values.
Tuples usually contain error strings, error numbers, and error locations.
The following is an example of a single exception:
Copy Code The code is as follows.
#!/usr/bin/python

# Define a function here.
def temp_convert(var):
   try:
      return int(var)
   except ValueError, Argument:
      print "The argument does not contain numbers\n", Argument

# Call above function here.
temp_convert("xyz");


The results of the execution of the above program are as follows:
Copy Code The code is as follows.
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'

Use raise to trigger an exception:
We can trigger the exception ourselves using the raise statement

The raise syntax is formatted as follows:

Copy Code The code is as follows.
raise [Exception [, args [, traceback]]]

The Exception is the type of the exception (e.g., NameError) and the parameter is an exception parameter value. This parameter is optional; if not supplied, the exception parameter is "None".
The last argument is optional (and rarely used in practice) and, if present, is the trace exception object.
Examples of raise usage:
An exception can be a string, class, or object. Most of the exceptions provided by Python's kernel are instantiated classes, which are arguments to an instance of a class.
Defining an exception is very simple, as shown below:
Copy Code The code is as follows.
def functionName( level ):
   if level < 1:
      raise "Invalid level!", level
      # The code below to this would not be executed
      # if we raise the exception

Note: In order to catch an exception, the "except" statement must throw a class object or string with the same exception.
For example, if we catch the above exception, the "except" statement would look like this:
Copy Code The code is as follows.
try:
   Business Logic here...
except "Invalid level!":
   Exception handling here...
else:
   Rest of the code here...

VII. Examples of user-defined exceptions
By creating a new Exception class, programs can name their own exceptions. Exceptions should typically inherit from the Exception class, either directly or indirectly.
The following is an example related to RuntimeError, which creates a class with the base class RuntimeError to output more information when an exception is thrown.
In the try statement block, the user-defined exception is followed by the execution of the except block statement, and the variable e is used to create an instance of the Networkerror class.

Copy Code The code is as follows.
class Networkerror(RuntimeError):
   def __init__(self, arg):
      = arg

After you define the above class, you can trigger the exception as shown below:
Copy Code The code is as follows.
try:
   raise Networkerror("Bad hostname")
except Networkerror,e:
   print


P.S. python standard exception
BaseExceptiona: the base class for all exceptions
SystemExitb python: interpreter request exit
KeyboardInterruptc: user interrupt execution (usually input ^C)
Exceptiond: base class for regular errors
StopIteratione: the iterator has no more values
GeneratorExita: generator (generator) exception to notify exit
SystemExith: Python Interpreter Requests Exit
StandardErrorg: Base class for all built-in standard exceptions.
ArithmeticErrord: the base class for all numerical calculation errors
FloatingPointErrord: Floating point calculation error
OverflowError: Numerical operation exceeds the maximum limit
ZeroDivisionError: divide (or take the mode) by zero (all data types)
AssertionErrord: assertion statement failure
AttributeError: the object does not have this attribute
EOFError: no built-in input, reached EOF flag
EnvironmentErrord: base class for operating system errors
IOError: input/output operation failure
OSErrord: operating system error
WindowsErrorh Windows: system call failure
ImportError: Failed to import modules/objects
KeyboardInterruptf: user interrupt execution (usually input ^C)
LookupErrord: base class for invalid data queries
IndexError: There is no index in the sequence that does not have this index.
KeyError: the key is not present in the mapping
MemoryError: memory overflow error (not fatal for Python interpreter)
NameError: object not declared/initialized (no attributes)
UnboundLocalErrorh: access to uninitialized local variables
ReferenceErrore: Weak reference attempts to access a garbage-collected object.
RuntimeError: general runtime error
NotImplementedErrord: methods not yet implemented
SyntaxError: Python Syntax Error
IndentationErrorg: Indentation Error
TabErrorg: Tab and space mixups
SystemError General Interpreter System Error
TypeError: invalid operation on type
ValueError: invalid parameter passed in
UnicodeErrorh: Unicode Related Errors
UnicodeDecodeErrori: Errors in Unicode Decoding
UnicodeEncodeErrori: Error while encoding Unicode
UnicodeTranslateErrorf: Error during Unicode Translation
Warningj: base class for warnings
DeprecationWarningj: warnings about deprecated features
FutureWarningi: a warning that the semantics of constructs will change in the future
OverflowWarningk: old warning about auto-raising to long integer (long)
PendingDeprecationWarningi: Warning that features will be deprecated
RuntimeWarningj: Warnings about suspicious runtime behavior.
SyntaxWarningj: Warnings about questionable syntax
UserWarningj: warnings generated by user code