Exception Handling in Python

Exception Handling in Python

Exception handling is one of the important task which is covered in every language in many ways. Python also supports exception handling in their own way. Python exception handling is similar to Java exception handling. Like Java try – catch block python also having similar try – except block.

Any code that you that you think is going to throw exception must be written inside the try block. If exception occurs then the control will automatically transfer to except block and the code written in the except block will get executed. There are some predefined or built-in exception classes in python whose super class is Exception. The exception classes are –

  • FileNotFoundError
  • PermissionError
  • InterruptedError
  • NameError
  • OverflowError
  • RuntimeError

And many more similar exception classes are there for specify the error or exception in python. You can refer to Python Doc
https://docs.python.org/3/library/exceptions.html for more details of exception. But don’t worry you no need to worry about keep remembering the names of above exception classes. What you can do is to use Exception class which is super of all other exception class.

Next part of exception is throwing the exception as and when you want your code to through it. So for doing that if your remember Java we are having throw statement. In python we are having raise statement to throw specific exception from try block which will get cached by except block. Here is the example to demonstrate simple use of try-except block and exception handling in Python.

Code to demonstrate the use of Exception Handling

Output of the above programs are as follows –

Happy Scenario of code where no Exception

Exception Handling Scenario

The second output is from except block. If you want to contribute feel free to comment and give output.