Last Updated:

What are exceptions in Python?

Python exception handling is necessary so that every time an exception occurs, the application does not crash. For this task, use the try/except, finally, and raise blocks. We will talk about them and how to create your own exceptions below.

What are exceptions in Python?

Exception hierarchy in Python

 

In the Python language, there are a huge number of built-in types of exceptions, but they all represent a certain hierarchy:

BaseException
+– SystemExit
+– KeyboardInterrupt
+– GeneratorExit
+– Exception
+– StopIteration
+– StopAsyncIteration
+– ArithmeticError
| +– FloatingPointError
| +– OverflowError
| +– ZeroDivisionError
+– AssertionError
+– AttributeError
+– BufferError
+– EOFError
+– ImportError
+– ModuleNotFoundError
+– LookupError
| +– IndexError
| +– KeyError
+– MemoryError
+– NameError
| +– UnboundLocalError
+– OSError
| +– BlockingIOError
| +– ChildProcessError
| +– ConnectionError
| | +– BrokenPipeError
| | +– ConnectionAbortedError
| | +– ConnectionRefusedError
| | +– ConnectionResetError
| +– FileExistsError
| +– FileNotFoundError
| +– InterruptedError
| +– IsADirectoryError
| +– NotADirectoryError
| +– PermissionError
| +– ProcessLookupError
| +– TimeoutError
+– ReferenceError
+– RuntimeError
| +– NotImplementedError
| +– RecursionError
+– SyntaxError
| +– IndentationError
| +– TabError
+– SystemError
+– TypeError
+– ValueError
| +– UnicodeError
| +– UnicodeDecodeError
| +– UnicodeEncodeError
| +– UnicodeTranslateError
+– Warning
+– DeprecationWarning
+– PendingDeprecationWarning
+– RuntimeWarning
+– SyntaxWarning
+– UserWarning
+– FutureWarning
+– ImportWarning
+– UnicodeWarning
+– BytesWarning
+– ResourceWarning

As you've noticed, all exceptions are a subclass of BaseException exceptions.

To understand everything, you need to take a closer look at the different types of exceptions that appear when an exception is thrown in Python code.

Try/Except blocks

 

To prevent the code from leading to an exception, it should be enclosed in the ry block. Here's an example:

try:

for i inrange(3):
print(3/i)
except:
print("Division by 0")
print("Exception was handled")

The application displayed a message because an exception was handled. Then there is the except block. If the type of exception is not defined, it will intercept everything. We can say that this is a common exception handler.

In the event that the code in the try block results in an exception, the interpreter will look for the except block specified below. The other part of the code will not be executed in try.

Exceptions in Python are especially useful if the application works with user input, since you never know what it can enter.

Example of several excepts in Python

 

A single try block can have multiple except blocks. Here are examples with different processing options:

a,b=1.0
try:
print(a/b)
print("This will not be printed")
print('10'+10)

exceptTypeError:
print exceptZeroDivisionError
:
print

After the interpreter detects the exception, it will check the except blocks of the corresponding try block, in which the exception types to be handled can be declared. If the interpreter finds a matching exception, it executes this block except.

In the example, the first statement leads to ZeroDivisionError. This error is handled in the ept block, but the statements in try after the first one are not executed. That's because after the first exception, subsequent instructions are skipped. If the common or matching blocks cannot be found except, the exception is not handled. Therefore, the remainder of the program does not start. However, if the exception is handled, the code after the except and finally blocks will be executed.

Example:

a,b=1.0
try:
print(a/b)
except:
print("You can't divide by 0")
print("Will this be printed?")

Consider the conclusion:

You can't divide by 0
Will this be printed?

Example of multiple exceptions in one except

You can use a single except block to handle multiple exceptions. To do this, you need to use parentheses, otherwise the interpreter will return a syntax error.

try:
print('10'+10)
print(1/0)
except(TypeError,ZeroDivisionError):
print("Invalid input")
Invalid input

Example: Common except after all except blocks

You can end all the individual blocks except in one common way. It is used to handle all exceptions that were not caught by a single except.

try:
print('1'+1)
print(sum)
print(1/0)
exceptNameError:
print(sum does not exist")
exceptZeroDivisionError:
print(You can't split by 0")
except:
print(Something went wrong...")
Something went wrong...

In the example, the first block statement attempts to concatenate a Python string with a number. This causes a TypeError error. When the interpreter encounters this problem, it checks the corresponding except block (the one that handles it).

You cannot place a separate statement between the try and except blocks:

try:
print(«1»)
print(«2»)
except:
print(«3»)

As a result, a syntax error will occur.

However, there can be only one default block or a common block of type except. The following code will cause an error: "default 'except:' mustbelast":

try:
print(1/0)
except:
raise
except:
print("Exception caught")
finally:
print("OK")
print("Bye")

Block finally in Python

The finally block can be added after the last exept block. He will execute the instruction under any conditions:

try:
print(1/0)
exceptValueError:
print(This is a value error)
finally:
print(This will be printed anyway.")
This will be printed anyway.

Traceback (most recent call last):
File “<pyshell#113>”, line 2, in<module>
print(1/0)
ZeroDivisionError: divisionbyzero

An example of if an exception will be caught in except:

try:
print(1/0)
exceptZeroDivisionError:
print(2/0)
finally:
print Nothing happens


Traceback (mostrecentcalllast):
File «<pyshell#1>», line 2, in<module>
print(1/0)
ZeroDivisionError: divisionbyzero

Duringhandlingoftheaboveexception, anotherexceptionoccurred:

Traceback (mostrecentcalllast):
File «<pyshell#1>», line 4, in<module>
print(2/0)
ZeroDivisionError: divisionbyzero

As you can see, the code in the finally block is executed anyway.

Raise keyword in Python

In some cases, you have to deal with problems by throwing exceptions. The usual print instruction will not work here:

raiseZeroDivisionError
Traceback (mostrecentcalllast):
File «<pyshell#2>», line 1, in<module>
raiseZeroDivisionError
ZeroDivisionError

Example of a division operation:

a,b=int(input()),int(input())# вводим 1 затем 0
if b==0:
raiseZeroDivisionError
Traceback (mostrecentcalllast):
File «<pyshell#2>», line 3, in<module>
raiseZeroDivisionError
ZeroDivisionError

User input to variables and b is converted to integers. After that, it is checked whether it corresponds to zero. If so, ZeroDivisionError will be called.

An example of if you add the same to try-except blocks (if you enter 1 and 0).

a,b=int(input()),int(input())
try:
if b==0:
raiseZeroDivisionError
except:
print("Division by 0")
print("Will this be printed?")
one
0
Division by 0
Will it be printed?

Here are a few more examples:

raiseKeyError
Traceback (mostrecentcalllast):
File “<pyshell#180>”, line 1, in<module>
raiseKeyError
KeyError

Example: Raise without a specific exception in Python

A programmer can use raise without specifying which exception to throw. In this case, the exception that occurred will be thrown. For this reason, it can only be applied to the except block.

try:
print(‘1’+1)
except:
raise
Traceback (mostrecentcalllast):
File “<pyshell#152>”, line 2, in<module>
print(‘1’+1)
TypeError: mustbestr, notint

Raise example with argument in Python

You can also specify an argument to a specific exception in raise. This is done with the help of additional exclusion details:

raiseValueError("Invalid value")
Traceback (most recent call last):
File "<pyshell#3>", line 1, in<module>
raiseValueError("Invalid value")
ValueError: Inappropriate value

Assert assertion in Python

Assert is a sanitary test for your paranoid, cynical self. If false is returned, it takes the statement as an argument and throws Python exceptions. Otherwise, performs a NOP (No-operation) operation.

assert(True)
# the code works further

An example of if the instruction were False:

assert(1==0)
Traceback (mostrecentcalllast):
File “<pyshell#157>”, line 1, in<module>
assert(1==0)
AssertionError

Here's another example:

try:
print(1)
assert2+2==4
print(2)
assert1+2==4
print(3)
except:
print("assertFalse.")
raise
finally:
print("OK")
print("Bye")

The conclusion is as follows:

1
2
assertFalse.
Хорошо
Traceback (mostrecentcalllast):
File “<pyshell#157>”, line 5, in<module>
assert 1+2==4
AssertionError

Assert assertions can be used to verify I/O validity in a function.

Example: Second argument for assert

To give additional information about the problem, provide the second argument:

assertFalse, "This is a problem"
Traceback (most recent call last):
File “<pyshell#173>”, line 1, in<module>
assertFalse,”This is a problem”
AssertionError: This is a problem

Declaring Native Python Exceptions

Now let's look at the process of creating your own exceptions by creating a new class from the Exception class. It can then be thrown as any other type of exception.

classMyError(Exception):
print

raiseMyError("errorMyError")
Traceback (most recent call last):
File “<pyshell#179>”, line 1, in<module>
raiseMyError("errorMyError")
MyError: errorMyError

Conclusion

 

The information we provide will help you set additional security for your code. Take advantage of Python exception handling, learn how to throw them and create your own.