Exception Handling
PYTHON EXCEPTION
- An exception can be defined as an unusual condition in a program resulting in the interruption in the flow of the program.
- Whenever an exception occurs, the program stops the execution, and thus the further code is not executed. Therefore, an exception is the run-time errors that are unable to handle to Python script. An exception is a Python object that represents an error
- Python provides a way to handle the exception so that the code can be executed without any interruption. If we do not handle the exception, the interpreter doesn't execute all the code that exists after the exception.
- Python has many built-in exceptions that enable our program to run without interruption and give the output. These exceptions are given below:
Common Exceptions
- Python provides the number of built-in exceptions, but here we are describing the common standard exceptions. A list of common exceptions that can be thrown from a standard Python program is given below.
- ZeroDivisionError: Occurs when a number is divided by zero.
- NameError: It occurs when a name is not found. It may be local or global.
- IndentationError: If incorrect indentation is given.
- IOError: It occurs when Input Output operation fails.
- EOFError: It occurs when the end of the file is reached, and yet operations are being performed.
THE PROBLEM WITHOUT HANDLING EXCEPTIONS
- As we have already discussed, the exception is an abnormal condition that halts the execution of the program.
- Suppose we have two variables a and b, which take the input from the user and perform the division of these values. What if the user entered the zero as the denominator? It will interrupt the program execution and through a ZeroDivision exception.
- Let's see the following example.
- Output:
- The above program is syntactically correct, but it through the error because of unusual input. That kind of programming may not be suitable or recommended for the projects because these projects are required uninterrupted execution. That's why an exception-handling plays an essential role in handling these unexpected exceptions. We can handle these exceptions in the following way.
PYTHON ERRORS AND BUILT-IN EXCEPTIONS
- We can make certain mistakes while writing a program that lead to errors when we try to run it. A python program terminates as soon as it encounters an unhandled error. These errors can be broadly classified into two classes:
- Syntax errors
- Logical errors (Exceptions)
PYTHON SYNTAX ERRORS
- Error caused by not following the proper structure (syntax) of the language is called syntax error or parsing error.
- Let's look at one example:
- As shown in the example, an arrow indicates where the parser ran into the syntax error.
- We can notice here that a colon : is missing in the if statement.
PYTHON LOGICAL ERRORS (EXCEPTIONS)
- Errors that occur at runtime (after passing the syntax test) are called exceptions or logical errors.
- For instance, they occur when we try to open a file(for reading) that does not exist (FileNotFoundError), try to divide a number by zero (ZeroDivisionError), or try to import a module that does not exist (ImportError).
- Whenever these types of runtime errors occur, Python creates an exception object. If not handled properly, it prints a traceback to that error along with some details about why that error occurred.
- Let's look at how Python treats these errors:
PYTHON BUILT-IN EXCEPTIONS
- Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are raised when corresponding errors occur. We can view all the built-in exceptions using the built-in local() function as follows:
- locals()['__builtins__'] will return a module of built-in exceptions, functions, and attributes. dir allows us to list these attributes as strings.
- The table below shows built-in exceptions that are usually raised in Python:
- If required, we can also define our own exceptions(Python.User-defined Exceptions) in.
- We can handle these built-in and user-defined exceptions in Python using try, except and finally statements.
EXCEPTION HANDLING IN PYTHON
- The try-expect statement
- If the Python program contains suspicious code that may throw the exception, we must place that code in the try block. The try block must be followed with the except statement, which contains a block of code that will be executed if there is some exception in the try block.
- Syntax
- Consider the following example.
- Output:
- We can also use the else statement with the try-except statement in which, we can place the code which will be executed in the scenario if no exception occurs in the try block.
- The syntax to use the else statement with the try-except statement is given below.
- Consider the following program.
- Output:
- The except statement with no exception Python provides the flexibility not to specify the name of exception with the exception statement.
- Consider the following example.
- The except statement using with exception variable We can use the exception variable with the except statement. It is used by using the as keyword. this object will return the cause of the exception
- Consider the following example:
- Output:
- Points to remember
- Python facilitates us to not specify the exception with the except statement.
- We can declare multiple exceptions in the except statement since the try block may contain the statements which throw the different type of exceptions.
- We can also specify an else block along with the try-except statement, which will be executed if no exception is raised in the try block.
- The statements that don't throw the exception should be placed inside the else block.
- Example
- Output:
- Declaring Multiple Exceptions
- The Python allows us to declare the multiple exceptions with the except clause. Declaring multiple exceptions is useful in the cases where a try block throws multiple exceptions.
- The syntax is given below.
- Consider the following example.
- Output:
- The try...finally block
- Python provides the optional finally statement, which is used with the try statement. It is executed no matter what exception occurs and used to release the external resource. The finally block provides a guarantee of the execution.
- We can use the finally block with the try block in which we can pace the necessary code, which must be executed before the try statement throws an exception.
- Syntax
- Example
- Output:
Raising exceptions
- An exception can be raised forcefully by using the raise clause in Python. It is useful in in that scenario where we need to raise an exception to stop the execution of the program.
- For example, there is a program that requires 2GB memory for execution, and if the program tries to occupy 2GB of memory, then we can raise an exception to stop the execution of the program.
- The syntax to use the raise statement is given below.
- Points to remember
- To raise an exception, the raise statement is used. The exception class name follows it.
- An exception can be provided with a value that can be given in the parenthesis.
- To access the value "as" keyword is used. "e" is used as a reference variable which stores the value of the exception.
- We can pass the value to an exception to specify the exception type.
- Example
- Output:
- Example: Raise the exception with message
- Output:
- Example
- Output:
CREATING CUSTOM EXCEPTION
- In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class.
- Here we created a new exception class i.e. User_Error. Exceptions need to be derived from the built-in Exception class, either directly or indirectly. Let’s look at the given example which contains a constructor and display method within the given class.
- Example
Comments
Post a Comment