Exception Handling
The try block contains the code that may raise an exception,
Each except block handles a specific exception type
You can have multiple except blocks to handle different exception types.
The first matching block will be executed. You can specify the exception type after except, €,
except Valuetrror:. f you don't specify a particular exception type, it will catch all exceptions
You can assign the exception instance to a variable using as. For example, except ValueError as
e.
The else block is executed if no exceptions occur in the try block
The finally block is always executed, regardless of whether an exception occurred or not. Itis
typically used to clean up resources.
You can handle multiple exception types in a single except block by enclosing them in
parentheses
The Exception class is the base class for all built-in exceptions. Handling Exception will catch any
exception that hasn't been handled by other except blocks
Handling a specific exception:
try:
# Code that might raise a Valuegrror
except Valuetrror
# Handle the ValueError exception
Handling multiple specific exceptions:
try:
# Code that might raise a ValueError or Typetrror
except (ValueError, Typeérror):
# Handle the ValueError or TypeError exception
Handling multiple specific exceptions with different handling logic:
try;
# Code that might raise a Valuetrror or Typeérror
except Valuetrror:
# Handle the ValueError exceptionexcept TypeError:
# Handle the TypeError exception
Handling any exception:
try:
# Code that might raise any exception
except Exception:
# Handle any exception
Handling any exception with exception information:
try:
# Code that might raise any exception
except Exception as e:
# Handle any exception and print the exception information
print ("Exception:", str(e))
Handling specific exceptions and any other exception:
try:
4# Code that might raise a Valuegrror, TypeError, or any other exception
except Valuetrror
# Handle the Valuefrror exception
except TypeError:
# Handle the Typefrror exception
except Exception as e:
# Handle any other exception
print("Exception:", str(e))
Handling exceptions in a loop:
for item in itens
try:
# Code that might raise an exception
except Exception:
# Handle the exception
Hani
ling exceptions and continuing the loop:
for item in itens:
try:
4 Code that might raise an exception
except Exception:
# Handle the exception
continue# Code to execute if no exception occurred
Handling exceptions and breaking out of the loop:
nL]: for item in items
try:
# Code that might raise an exception
except Exception:
# Handle the exception
break
# Code to execute if no exception occurred
Raising an exceptior
nL]: | try:
# Code that might raise an exception
if condition:
raise Valuetrror(“Invalid value")
except ValueError as e:
# Hondle the raised Valueérror
print ("Exception:", str(e))
Reraising an exception:
n try:
# Code that might raise an exception
except Exception as e:
# Handle the exception
raise
Hani
19 exceptions with an else bloc
A try:
# Code that might raise an exception
except Exception:
# Handle the exception
els
# Code to execute if no exception occurred
Handling exceptions with a finally block:
nL]: | try:
# Code that might raise an exception
except Exception:
# Handle the exception
finally:# Code to execute regardless of exceptions
Using multiple levels of exception handling:
nf]: | try:
# Code that might raise an exception
except Valuerror
# Handle the ValueError exception
try:
# Code that might raise another exception
except AnotherException:
# Handle the AnotherException exception
finally:
# Code to execute regardless of exceptions in the inner try-except block
except Exception:
# Handle any other exception
Handling exceptions raised by built-in functor
n try:
result = int("123")
except Valuetrror
# Handle the ValueError exception
Handling exceptions raised by external libraries:
n try:
import external_Library
except Inportérror:
# Handle the ImportError exception
Handling exceptions with 2 custom error message:
nbd try
# Code thet might raise an exception
except ValueError as e:
# Handle the Valueérror exception and print a custom error message
print(*Valuetcrer occurred:”, str(e))
Handling exceptions with multiple except blocks for the same exception type:
nL]: | try:
4 Code that might raise a Valuegrror
except Valuetrror as e:
# Handle the ValueError exception with specific handling Logic
except Valuetrror as e:# Handle the ValueError exception with different handling Logic
Handling exceptions with a base exception class:
try:
# Code that might raise any exception
except Exception:
# Handle any exception using the base Exception class
Handling exceptions in 2 function and propagating the exception:
def sone_function():
try:
# Code that might raise an exception
except Exception:
# Handle the exception
try:
some_function()
except Exception:
# Handle the propagated exception
Hans
1g exceptions with traceback information:
import traceback
try:
# Code that might raise an exception
except Exception as e:
# Handle the exception and print the traceback information
traceback.print_exe()
Handling exceptions with specific error codes:
try:
# Code that might raise an exception
except Exception as e:
if str(e) == "Error Code 123"
# Handle the specific error code
else
# Handle any other exception
Handling exceptions without any handling logi
try:
# Code that might raise an exceptionexcept:
# No specific handling Logic, just suppress the exception
pass
Handling exceptions and logging the error:
In [ }: dmport Logging
try:
# Code that might raise an exception
except Exception as e:
# Handle the exception and Log the error
Logging.error( "Exception occurred: %s", str(e))
Handling exceptions and executing cleanup code in the finally block:
In [ ]: | try:
File = open("data.txt", "r")
try:
# Code that might raise an exception
except Exception:
# Handle the exception
finally:
# Cleanup code to always close the file
file.close()
except FileNotFoundérror:
# Handle the FileNotFoundérror exception