Wednesday, April 24, 2024
HomeProgrammingA Information to Python Exception Dealing with — SitePoint

A Information to Python Exception Dealing with — SitePoint


On this article, we’ll have a look at the right way to deal with errors and exceptions in Python — an idea generally known as “exception dealing with”.

There are often two sorts of errors you’ll expertise whereas programming in Python: syntax errors, and exceptions.

Any error ensuing from invalid syntax, indentation or programming construction is usually considered a syntax error. When a syntax error happens, this system crashes on the level the syntax error occurred.

An exception is an anomaly that disrupts the conventional move of a pc program. When exceptions happen, we’re anticipated to deal with these exceptions to make sure that our packages don’t crash abruptly.

Exception dealing with is the method whereby checks are applied in pc packages to deal with errors — whether or not anticipated or not — that will happen through the execution of our packages. (Python tends to have extra of a “do the factor and say sorry” type of programming than most different languages, as mentioned right here and right here.)

Python Exception Dealing with

Python, like each different programming language, has a approach of dealing with exceptions that happen throughout a program’s execution. Which means that exceptions are dealt with gracefully: our Python program doesn’t crash. When an error happens at runtime in a program that’s syntactically right, Python makes use of the attempt assertion and besides clause to catch and deal with exceptions.

Since many of the exceptions are anticipated, it’s essential to be extra focused or particular with exception dealing with in our Python packages. Particular exception dealing with makes debugging of packages simpler.

Some Normal Python Exceptions

Python has a listing of built-in exceptions used to deal with totally different exceptions. Under are some built-in Python Exceptions.

SN Exception Title Description
1 Exception All user-defined exceptions also needs to be derived from this class.
2 ArithmeticError The bottom class for these built-in exceptions which are raised for numerous arithmetic errors.
3 BufferError Raised when a buffer associated operation can’t be carried out.
4 LookupError The bottom class for the exceptions which are raised when a key or index that’s used on a mapping or sequence is invalid.
5 AssertionError Raised when an assert assertion fails.
6 AttributeError Raised when an attribute reference or task fails.
7 ImportError Raised when the import assertion has troubles attempting to load a module.
8 IndexError Raised when a sequence subscript is out of vary.
9 KeyError Raised when a mapping (dictionary) key is just not discovered within the set of present keys.
10 NameError Raised when an area or international identify is just not discovered.
11 OverflowError Raised when the results of an arithmetic operation is simply too giant to be represented.
12 RuntimeError Raised when an error is detected that doesn’t fall in any of the opposite classes.
13 StopIteration Raised by built-in operate subsequent() and an iterator’s __next__() technique to sign that there are not any additional gadgets produced by the iterator.
14 SyntaxError Raised when the parser encounters a syntax error.
15 TypeError Raised when an operation or operate is utilized to an object of inappropriate kind.
16 ValueError Raised when an operation or operate receives an argument that has the suitable kind however an inappropriate worth.
17 ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.
18 FileExistsError Raised when attempting to create a file or listing which already exists.
19 FileNotFoundError Raised when a file or listing is requested however doesn’t exist.

Dealing with Python Exceptions with the attempt to besides Statements

The attempt and besides blocks are used for exception dealing with in Python. The syntax can appear like this:

attempt:
    
besides: 
    

The attempt block accommodates a bit of code that may elevate an exception, whereas the besides block homes some code that handles the exception.

Let’s take a easy instance under:

print(3/0)

The code above will generate an error message whereas this system terminates:

Traceback (most up-to-date name final):
  File "/house/ini/Dev/Tutorial/sitepoint/exception.py", line 53, in <module>
    print(3/0)
ZeroDivisionError: division by zero

The road of code that throws the exception will be dealt with as follows:

attempt:
    print(3/0)
besides ZeroDivisionError:
    print("Can't divide quantity by Zero")

Within the instance above, we place the primary print assertion throughout the attempt block. The piece of code inside this block will elevate an exception, as a result of dividing a quantity by zero has no which means. The besides block will catch the exception raised within the attempt block. The attempt and besides blocks are sometimes used collectively for dealing with exceptions in Python. As an alternative of the earlier error message that was generated, we merely have “Can’t divide quantity by Zero” printed within the console.

A number of Python Excepts

There are circumstances the place two or extra besides blocks are used to catch totally different exceptions in Python. A number of besides blocks assist us catch particular exceptions and deal with them otherwise in our program:

attempt:
    quantity = 'one'
    print(quantity + 1)
    print(block)
besides NameError:
    print("Title is undefined right here")
besides TypeError:
    print("Cannot concatenate string and int")

Right here’s the output of the code above:

Cannot concatenate string and int

From the instance above, now we have two besides blocks specifying the sorts of exceptions we wish to deal with: NameError and TypeError. The primary print assertion within the attempt block throws a TypeError exception. The Python interpreter checks via every besides clause to seek out the suitable exception class, which is dealt with by the second besides block. “Can’t concatenate string and int” is printed within the console.

The second print assertion within the attempt block is skipped as a result of an exception has occurred. Nonetheless, any code after the final besides clause shall be executed:

attempt:
    quantity = 'one'
    print(quantity + 1)
    print(block)
besides NameError:
    print("Title is undefined right here")
besides TypeError:
    print("Cannot concatenate string and int")

for identify in ['Chris', 'Kwame', 'Adwoa', 'Bolaji']:
    print(identify, finish=" ")

Right here’s the output of the code above:

Cannot concatenate string and int
Chris Kwame Adwoa Bolaji

The for loop after the attempt and besides blocks is executed as a result of the exception has been dealt with.

A generic Python besides

We are able to have a generic besides block to catch all exceptions in Python. The generic besides block can be utilized alongside different particular besides blocks in our program to catch unhandled exceptions. It’s logical to put probably the most generic besides clause in spite of everything particular besides blocks. This can kick in when an unhandled exception happens. Let’s revise our earlier instance with a basic besides block coming in final:

names = ['Chris', 'Kwame', 'Adwoa', 'Bolaji']
attempt:
    print(names[6])
    quantity = 'one'
    print(quantity + 1)
    print(block)
besides NameError:
    print("Title is undefined right here")
besides TypeError:
    print("Cannot concatenate string and int")
besides:
    print('Sorry an error occured someplace!')

for identify in names:
    print(identify, finish=" ")

Right here’s the output of the code above:

Sorry an error occured someplace!
Chris Kwame Adwoa Bolaji

An IndexError exception happens, nonetheless, because it isn’t dealt with in any of the required besides blocks. The generic besides block handles the exception. The assertion within the generic block is executed and the for loop after additionally it is executed, with the respective output printed within the console.

The elevate assertion

Generally in our Python packages we would wish to elevate exceptions in sure situations that don’t match our requirement utilizing the elevate key phrase. The elevate assertion consists of the key phrase itself, an exception occasion, and an optionally available argument. Let’s take a code snippet under:

def validate_password(password):
    if len(password) < 8:
        elevate ValueError("Password characters lower than 8")
    return password

attempt:
    user_password = enter('Enter a password: ')
    validate_password(user_password)
besides ValueError:
    print('Password ought to have extra characters')

The elevate ValueError checks if the password meets the required size and raises the required exception if the situation isn’t met. Stack OverFlow examines why it’s OK to lift exceptions as a substitute of simply printing to the console:

Elevating an error halts your complete program at that time (except the exception is caught), whereas printing the message simply writes one thing to stdout — the output is perhaps piped to a different instrument, or somebody won’t be working your software from the command line, and the print output might by no means be seen.

Elevate an exception, to delegate the dealing with of that situation to one thing additional up the callstack.

The else clause

The else clause will be added to the usual attempt and besides blocks. It’s positioned after the besides clause. The else clause accommodates code that we wish executed if the attempt assertion doesn’t elevate an exception. Let’s think about the next code:

attempt:
    quantity = int(enter('Enter a quantity: '))
    if quantity % 2 != 0:
        elevate ValueError
besides ValueError:
    print("Quantity have to be even")
else:
    sq. = quantity ** 2
    print(sq.)

When a person enters a good quantity, our code runs with out elevating exceptions. Then the else clause executes. We now have the sq. of our even quantity printed within the console. Nonetheless, exceptions that will happen within the else clause aren’t dealt with by the earlier besides block(s).

The lastly clause

The lastly clause will be added to attempt and besides blocks and needs to be used the place mandatory. Code within the lastly clause is at all times executed whether or not an exception happens or not. See the code snippet under:

attempt:
    with open('robots.txt', 'r', encoding='UTF-8') as f:
        first_line = f.readline()
besides IOError: 
    print('File not discovered!')
else:
    upper_case = first_line.higher()
    print(upper_case.index('x'))
lastly:
    print('The Python program ends right here!')

Right here’s the output of the code above:

The Python program ends right here!
Traceback (most up-to-date name final):
  File "/house/ini/Dev/python/python_projects/further.py", line 89, in <module>
    print(upper_case.index('x'))
ValueError: substring not discovered

Within the instance above, we’re trying to learn a robots.txt file within the attempt clause. Since there’s no exception raised, the code within the else clause is executed. An exception is raised within the else clause as a result of the substring x wasn’t discovered within the variable upper_case. When there’s no besides clause to deal with an exception — as seen the code snippet above — the lastly clause is executed first and the exception is re-raised after.

The Python documentation explains it like so:

An exception may happen throughout execution of an besides or else clause. Once more, the exception is re-raised after the lastly clause has been executed.

Exception Teams

ExceptionGroup grew to become accessible in Python 3.11. It supplies a method of elevating a number of unrelated exceptions. The popular syntax for dealing with ExceptionGroup is besides*. The syntax for exception teams appears like this:

ExceptionGroup(msg, excs)

When initialized, exception teams take two arguments, msg and excs:

  • msg: a descriptive message
  • excs: a sequence of exception subgroups

Let’s create an occasion of ExceptionGroup:

eg = ExceptionGroup('group one', [NameError("name not defined"), TypeError("type mismatch")])

When instantiating an exception group, the record of exception subgroups can’t be empty. We’ll elevate an occasion of the exception group we created earlier:

elevate eg

Right here’s the output of the code above:

+ Exception Group Traceback (most up-to-date name final):
|   File "<string>", line 10, in <module>
  | ExceptionGroup: group one (2 sub-exceptions)
  +-+---------------- 1 ----------------
    | NameError: identify not outlined
    +---------------- 2 ----------------
    | TypeError: kind mismatch
    +------------------------------------

The displayed traceback exhibits all exception subgroups contained within the exception group.

As acknowledged earlier, ExceptionGroup is healthier dealt with with the besides* clause, as a result of it may possibly pick every particular exception within the exception group. The generic besides clause will solely deal with the exception group as a unit with out being particular.

See the code snippet under:

attempt:
    elevate ExceptionGroup('exception group', [NameError("name not defined"), TypeError("type mismatch"), ValueError("invalid input")])
besides* NameError as e:
    print("NameError dealt with right here.")
besides* TypeError as e:
    print("TypeError dealt with right here.")
besides* ValueError:
    print("ValueError dealt with right here.")

Right here’s the output of that code:

NameError dealt with right here.
TypeError dealt with right here.
ValueError dealt with right here.

Every besides* clause handles a focused exception subgroup within the exception group. Any subgroup that’s not dealt with will re-raise an exception.

Person-defined Exceptions in Python

Constructed-in exceptions are nice, however there could also be a necessity for customized exceptions for our software program undertaking. Python permits us to create user-defined exceptions to go well with our wants. The Python Documentation states:

All exceptions have to be situations of a category that derives from BaseException.

Customized exceptions are derived by inheriting Python’s Exception class. The syntax for a customized exception appears like this:

class CustomExceptionName(Exception):
    cross
attempt:
    cross
besides CustomExceptionName:
    cross

Let’s create a customized exception and use it in our code within the following instance:

class GreaterThanTenError(Exception):
    cross

attempt:
    quantity = int(enter("Enter a quantity: "))
    if quantity > 10:
        elevate GreaterThanTenError
besides GreaterThanTenError:
    print("Enter higher than 10")
else:
    for i in vary(quantity):
        print(i ** 2, finish=" ")
lastly:
    print()
    print("The Python program ends right here")

Within the instance above, we create our personal class with an exception identify known as GreaterThanTenException, which inherits from the Exception superclass. We place in it some code that will elevate an exception within the attempt block. The besides block is our exception handler. The else clause has code to be executed if no exception is thrown. And lastly, the lastly clause executes regardless of the result.

If a person of our Python program inputs a quantity above 10, a GreaterThanTenError shall be raised. The besides clause will deal with exceptions, after which the print assertion within the lastly clause is executed.

Conclusion

On this tutorial, we’ve realized the primary distinction between syntax errors and exceptions. We’ve additionally seen {that a} syntax error or exception disrupts the conventional move of our program.

We’ve additionally realized that the attempt and besides statements are the usual syntax for dealing with exceptions in Python.

Exception dealing with is necessary when constructing real-world purposes, since you wish to detect errors and deal with them appropriately. Python supplies an extended record of in-built exceptions that show helpful when dealing with exceptions.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments