Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

What is exception handling in Python?

When I type say 3/0 at python prompt, I get an error as follows.

>>> 3 / 0

OUTPUT

Traceback (most recent call last):
File "", line 301, in run code
File "", line 1, in
ZeroDivisionError: division by zero

How to handle errors/exceptions in python?


1 Answer
Manogna

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.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.