Exception Handling in Python
Exception Handling in Python
Exceptions:
● Exceptions are errors that occur during the execution of a program.
● These errors are not necessarily caused by syntax errors, but rather
unexpected conditions or inputs.
● Examples of exceptions include division by zero, accessing an array out of
bounds, or trying to open a file that does not exist.
User-defined exceptions:
● User-defined exceptions are exceptions that are created by the
programmer.
● These exceptions can be used to handle specific errors that are not
covered by built-in exceptions.
Raising exceptions:
● Exceptions can be raised using the 'raise' keyword.
● This allows the programmer to intentionally trigger an exception under
certain conditions.
Lovejeet Arora
Computer science | Informatics Practices CUET 2023
2
Handling exceptions:
● Exceptions can be handled using the 'try' and 'except' blocks.
● The 'try' block contains the code that may raise an exception, and the
'except' block specifies how to handle the exception if it occurs.
Catching exceptions:
● Exceptions can be caught using the 'except' block.
● The 'except' block contains the code that is executed if an exception
occurs in the 'try' block.
Lovejeet Arora
Computer science | Informatics Practices CUET 2023
3
● Exceptions should be specific and provide useful information about the
error.
● Exception handling should be tested thoroughly to ensure that it works as
intended.
⭐⭐⭐⭐
Lovejeet Arora