home PYTHONJAVA
 

Python3 mistakes and exceptions

As a Python learner, when you initially learn Python programming, you will regularly observe some blunder messages. We didn't make reference to them in the past segment. We will present them in this section.

Python has two kinds of blunders that are anything but difficult to distinguish: linguistic structure mistakes and exemptions.

Syntax error

Python's sentence structure blunders, or parsing mistakes, are regular to apprentices, as in the accompanying examples

>>>while True print< /span>('Hello world') File "<stdin>", line 1, in ? while True print('Hello world')< /span> ^ SyntaxError: invalid syntax

In this precedent, the capacity print() is checked for blunders, which is feeling the loss of a colon (:) before it.

The parser brought up the line that was in blunder and denoted a little bolt at the area of the mistake discovered first.

Exception

Even if the language structure of the Python program is right, a blunder may happen while running it. Blunders recognized amid runtime are called special cases.

Most special cases are not taken care of by the program and are introduced here as blunder messages:

>>>10 * (1 /0) Traceback (most recent call last ): File "<stdin>", line 1, in ? ZeroDivisionError: division by zero >>> 4 + Spam*3 Traceback (most recent call last ): File "<stdin>", line 1, in ? NameError: name 'spam' is not defined >>> '2 ' + 2 Traceback (most recent call last ): File "<stdin>", line 1, in ? TypeError: Can't convert 'int' object to str implicitly

Exceptions show up in various kinds, and these sorts are printed as a feature of the data: The sorts in the precedents are ZeroDivisionError, NameError, and TypeError.

The front piece of the mistake message demonstrates the setting in which the exemption happened and shows the particular data as a call stack.

Exception handling

In the accompanying model, let the client enter a substantial number, yet enable the client to interfere with the program (utilizing Control-C or the technique given by the working framework). Client interfered with messages will raise a KeyboardInterrupt exemption.

>>>while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! That was no valid number. Try again ")
The

try proclamation fills in as follows;

  • First, execute the attempt proviso (the announcement between the watchword attempt and the catchphrase except)
  • If no special case happens, the aside from statement is disregarded and the attempt proviso finishes after execution.
  • If a special case happens amid the execution of the attempt provision, the remainder of the attempt proviso will be disregarded. In the event that the sort of the special case coordinates the name after aside from, the comparing with the exception of provision will be executed. At long last execute the code after the attempt proclamation.
  • If an exemption does not coordinate any aside from, at that point the special case will be passed to the upper attempt.

An attempt explanation may contain various aside from conditions to deal with various explicit special cases. At most just a single branch will be executed.

The

handler will just deal with special cases in the relating attempt condition, not exemptions in other attempt handlers.

An special case provision can deal with different exemptions in the meantime. These exemptions will be set in enclosures as a tuple, for instance:

except ( RuntimeError, TypeError, NameError): pass

The last aside from condition can overlook the name of the special case and it will be utilized as a trump card. You can utilize this technique to print a blunder message and after that toss the special case once more.

import sys try: f= open('myfile.txt') s= f.readline() i= int(s.strip()) except OSError as err: print(" OS blunder: {0}".format(err)) except ValueError: print(" Could not change over information to an integer.") except: print(" Unexpected error:", sys.exc_info()[0]) raise
The

try aside from articulation additionally has a discretionary else condition. In the event that you utilize this condition, you should put it after all the aside from provisos. This condition will be executed when there is no special case in the attempt statement. E.g:

for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print('cannot open', arg) else: print(arg, 'has', len(f.readlines()), 'lines') f.close()

It's smarter to utilize the else provision than to put every one of the announcements in the attempt statement, so you can dodge unforeseen special cases that are not gotten by with the exception of.

Exception taking care of does not just arrangement with special cases that happen straightforwardly in the attempt proviso, yet additionally handles exemptions tossed in capacities brought in provisos (or even in a roundabout way called capacities). For example:

>>>def this_fails() : x= 1/0 >>> try: this_fails() except ZeroDivisionError as err: print('Handling run-time error:', err) Handling run-time error: int division or modulo by zero

Throw an exception

Python uses the raise statement to throw a specified exception. For example:

>>>raise NameError('HiThere') Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: HiThere

raise The only parameter that specifies the exception to be thrown. It must be an exception instance or an exception class (that is, a subclass of Exception ).

If you just want to know if this throws an exception and doesn't want to handle it, then a simple raise statement can throw it again.

>>>try: raise NameError('HiThere') except NameError: print('An exception flew by!') raise An exception flew by! Traceback (most recent call last): File "<stdin>", line 2, in ? NameError: HiThere

User-defined exception

You can have your own exception by creating a new exception class. Exception classes inherit from the Exception class and can be inherited directly or indirectly, for example:

>>>class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) >>> try: raise MyError(2*2) except MyError as e: print('My exception occurred, value:', e.value) My exception occurred, value: 4 >>> raise MyError('oops!') Traceback (most recent call last): File "<stdin>", line 1, in ? __main__.MyError: 'oops!'

The names of most exceptions end with "Error", just like the standard exception name.


Define cleanup behavior

The

try statement has an optional clause that defines the cleanup behavior that will be performed under any circumstances. For example:

>>>try: ... raise KeyboardInterrupt ... finally: ... print('Goodbye, world!') ... Goodbye, world! Traceback (most recent call last ): File "<stdin>", line 2, in <module< /span>> KeyboardInterrupt

The above model will execute paying little heed to whether there is a special case in the attempt condition.

If an exemption is tossed in the attempt statement (or in the aside from and else conditions) with no special case capturing it, at that point the exemption will be tossed again after the at long last proviso is executed. .

The following is an increasingly confounded precedent (with the aside from lastly provisos in a similar attempt statement):

>>>def divide(x, y): try: result = x / y except ZeroDivisionError: print("division by zero!") else: print("result is", result) finally: print("executing finally clause") >>> divide(2, 1) result is 2.0 executing finally clause >>> divide(2, 0) division by zero! executing finally clause >>> divide("2", "1") executing finally clause Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str'

Predefined cleanup behavior

Some objects characterize standard cleanup conduct, paying little respect to whether the framework effectively utilized it, and once it isn't required, at that point this standard cleanup conduct will be performed.

This model shows endeavoring to open a document and afterward print the substance to the screen:

for line in open("myfile.txt"): print(line, end="")

The issue with this code is that when the execution is finished, the document will stay open and not shut.

The catchphrase with proclamation guarantees that items, for example, documents will accurately execute their cleanup strategies after they are used:

with open ("myfile.txt") as f: for line in f: print(line, end="")

After the above code is executed, regardless of whether there is an issue amid preparing, the document f will dependably be shut.






welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.