Error handling in Python

Hello

I am new to Python and just finished the 15 min lecture on Error handling in Python using the “try” and “except” blocks. It appears that we need to have prior knowledge of the error syntax to handle exceptions. This means I probably have to run my code without error handling and then handle them based on the errors that I see as the “except” construct takes them as argument

I am from scripting background and we do an independent error handling based on “if” constructs and not depend on the syntax of the error itself for catching those

BTW, on a lighter note is this not a catch-22 situation ? For handling error I need to make an error first to know the syntax ?

Harish

Hi,

with python try and except method you can handel error in explicit or implicit way.
if you mantion some error name then it will specipficaly catch that error. So for example if you want to catch value error then you need to write following code:

try:
 <some code>
except (ValueError): # Value error
  <some code>

but if you want to catch all error without any name then it must be like below code example :

try:
 <some code>
except : # all errors
  <some code>

this will catch all errors.

you can also nest except errors:

try:
 <some code>
except(ValueError) : # Value error
  <some code>
except(TypeError): # Type Error
 <some code>
except : # all other error
<some code>

i hope this wil help you.

2 Likes