Friday, December 15, 2017

Exceptions in Python

Exceptions are event occurred during your program execution.that normally cause your program to stop actually.it usually means some error has been encountered.And your program simply does not know how to deal with it.So take an example of exception code.

eg:

student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

last_name = student["last_name"]

Output:
KeyError: 'last_name'

To handle this scenario grecfully.we use try and except blog to handle this code.
So let's take another example with exception handled.

eg:
student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

try:
      last_name = student["last_name"]
except KeyError:
      print("Some error occurred")

print("this code executed!!!!")

Output:

Some error occurred
This code executed!!!

Note both try and except block can have more than one line of code.
There can be many error occurred  like TypeError.Can be many other too.

eg:
student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

student["last_name"] = "Tripathi"

try:
      last_name = student["last_name"]
      number_last_name = 3 + last_name
except KeyError:
      print("Some error occurred")

print("this code executed!!!!")

Output:

TypeError unsupported operand types .if you have noticed  this code executed! does not execute because we are only catching KeyError.So let's take another example.

eg:

student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

student["last_name"] = "Tripathi"

try:
      last_name = student["last_name"]
      number_last_name = 3 + last_name
except KeyError:
      print("Some error occurred")
except TypeError:
      print("I can add multiple together")

print("this code executed!!!!")

Output:

I can add multiple together
This code executed!!!

you can also generic exception like

eg:
student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

student["last_name"] = "Tripathi"

try:
      last_name = student["last_name"]
      number_last_name = 3 + last_name
except Exception:
      print("Some error occurred")

print("this code executed!!!!")

And you can also add finally at the end of except block.

No comments: