What is exception handling in Python?

PythonServer Side ProgrammingProgramming

An error is something that goes wrong in the program at the compile time like a syntactical error.

For example.

'abe' = 5

OUTPUT

SyntaxError: can't assign to literal

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not always fatal. If the exceptions are not handled error messages show up when the code is executed or run.

In general, when a Python script encounters an error that it can’t handle, it raises an exception and creates an exception object.

Usually, the script handles the exception immediately. If it doesn’t do so, then the program will terminate and print a traceback to the error along with its details. For example

abe < 5

OUTPUT

Traceback (most recent call last):
File "C:/Users/TutorialsPoint1/~.py", line 1,
 in <module>
abe < 5
NameError: name 'abe' is not defined

Exceptions are convenient in many ways for handling errors and special conditions in a program. When you think that you have a code which can produce an error then you can use exception handling.

raja
Published on 07-Dec-2017 11:11:20
Advertisements