Handling exceptions

Errors:

Compile time:– like syntactical error
Logical error:– wrong output
Run time:– like zero divsionerror(mistake by user)

Python Exception Handling – Try, Except and Finally

Finally:— finally block will be executed if we get error as well as if we do not get the error.

When these exceptions occur, it causes the current process to stop and passes it to the calling process until it is handled. If not handled, our program will crash.
For example, if function A calls function B which in turn calls function C and an exception occurs in function C. If it is not handled in C, the exception passes to B and then to A.

Output:—-

Output: —

Random Choice:—

we run this program—which illustrates almost every conceivable exception handling scenario, a few times, we’ll get different output each time

Output:—
Run first time:—
.

Second time:—-

(every time you get different output)

Defining our own exceptions

In Python, users can define such exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from Exception class. Most of the built-in exceptions are also derived form this class.

we have created a user-defined exception called CustomError which is derived from the Exception class. This new exception can be raised, like other exceptions, using the raise statement with an optional error message.

When we are developing a large Python program, it is a good practice to place all the user-defined exceptions that our program raises in a separate file. Many standard modules do this. They define their exceptions separately as exceptions.py or errors.py (generally but not always).

Open chat