Python Try Catch Exceptions Tutorial – POFTUT

Python Try Catch Exceptions Tutorial

As a developer, we have a lot of thoughts about the applications and features. Implementing them a tedious task. During the implementation, we can make mistakes. Those mistakes can be related to applications logic or technical. These errors will cause problems while the application is running. We call this type of problems as exceptions. We can not prevent all exceptions but we can create some mechanisms to handle these situations. In this tutorial, we will look at how to handle these exceptions.

What is An Exception

Some of us may be familiar with exceptions but there may be others those do not have any idea about exceptions. Exceptions are unexpected error situations where applications generally stop working. Sometimes it will not stop working but will not work properly either.

Here is an example of how an exception occurs. Our applications get input from the user and multiple given numbers. But there will be an exception if the user inputs string. The filename is .

When we call our application like below by providing a character like othera then a number we will get an exception.

What is An Exception

What is An Exception

We also get the exception type. Python provides a different type of exceptions for different situations. In this code the exception type is TypeError .

Exception Types

As there are a lot of different libraries and function there is a different type of exceptions. Here some of the most popular of them.

  • Exception is the generic and base class for all exceptions
  • StopIteration exception raised when the next() method of an iterator does not point to any object.
  • SystemExit exception raised by the sys.exit() function.
  • StandardError exception is a base class and exception for all built-in exceptions except StopIteration and SystemExit.
  • ArithmeticError exception is base class for all error that occurs during mathematical and arithmetic calculations and operators
  • OverFlowError exception raised when calculation exceeds the maximum limit for given numerical type.
  • ZeroDivisionError exception raised when a division or modulo by zero takes place for numerical operations.
  • AssertionError raised in case of failure of the assert Python programming language statement.
  • AttributeError exception raised in case of failure of attribute reference or assignment.
  • EOFError exception raised when there is no input or the end of a file is reached.
  • ImportError exception raised when an import Python programming language statement fails.
  • KeyboardInterrupt exception raised when the user interrupts the execution of the application with Linux kill command or pressing CTRL+C keyboard shortcut.
  • LookupError exception raised for all lookup errors.
  • IndexError exception raised when an index is not found in the array, list in a sequence.
  • KeyError exception raised when the specified key is not found in the dictionary.
  • NameError exception raised when an identifier is not found in the local or global namespace.
  • UnboundLocalError exception raised when trying to access a local variable in a function, method, module but no value has been assigned to it.
  • EnvironmentError exception is based class for all exceptions that occur outside of the Python Environment.
  • IOError exception raised when an input/output operations fail, such as writing a file failed or a file can not be opened.
  • SyntaxError exception raised when there is an error related with the Python Syntax.
  • IndentationError exception raised when indentation is not specified and used properly to catch code block.
  • SystemError exception raised when the Python interpreter finds and internal problem.
  • TypeError exception raised when an operation, function, method is attempted to get, set different type of variable or data type.
  • ValueError exception raised when built-in function fora data type has the valid type of arguments, but the arguments have invalid values.
  • RuntimeError exception raised when the raised exception or error do not suit any specific category.
  • NotImplementedError exception raised when an abstract method which is not implemented tried to be used.
LEARN MORE  C# Programming Language Null Reference Exception and Solution

Catch An Exception with Try and Except

Now we want to prevent this type of bugs and exceptions programmatically. Python provides a mechanismtry which is used to detect exceptions in the given block of the code. We will put the potential error block into liketry below. Here we guess that lineprint(num1-num1) can raise an exception.

When we run by providing a character like ita will not raise an exception. It simple skip to the codeexcept block which will run if an exception is raised. Then the application will flow in a normal situation.

Handle An Exception with Try and Except

Handle An Exception with Try and Except

Catching Specific Exceptions

In the previous example, we have fired a single type of exception with the codeexcept block. But we can catch a specific type of exception and ignoring others. As we remember from the first example we get the exceptionTypeError. If we only need to catch an exceptionTypeError and ignore others we will specify toTypeError the likeexcept below.

echo '

Catching Specific Exceptions

Catching Specific Exceptions

Else If No Exception Raised

We generally expect to raise some exception while running critical code. But in some cases, there will be no error or exception. We can define some code to execute if there is no error and exception with the else keyword. We will put the code we want to run if there is no error or exception inside else keyword block. In this example, we will print screen “There is no exception” if there is no error or exception.

LEARN MORE  What Is Null Pointer Exception In Java and How To Fix?

Catch Multiple Type Exceptions

We may need to catch multiple exceptions in a single except code block. We will provide the exception types in brackets by separating them with command (TypeA , TypeB , TypeC , ...)

In this example we will catch both TypeError and ZeroDivisionError .

Run Code After Exception with Finally

While checking exceptions in try code block we may need to execute some come whatever happens even try code block works or except code block works. We will use finally code block to complete the try-except blocks. After the try-except blocks finally code block will be run. This is generally used to release resources like file, database connection or revert operations used in try code block.

In this example we will close file handle in the finally code block whether previous codes blocks works or raise an exception .

Raise Exception

Up to now, we have handled self-raised exceptions. We can also raise an exception manually without waiting for a user input other any change. We will use keywordraise in order to raise an exception manually. In this example, we will raise typeZerrorDivisionError exception.

LEARN MORE  Linux "Command Not Found" Error And Solution

Raise Exception

Raise Exception

User-Defined Exceptions

While programming enterprise applications and libraries we will need to create our exception type library too. We may need to provide operational exceptions like invalid move operation for files. We can define our own user-defined exceptions by using classRuntimeError like below. We will put the following code into

and we can raise as we did before after importing

Leave a Reply

Your email address will not be published. Required fields are marked *