Klaidos (exception'ai)

Exception'o pavyzdys

Prašome skaičiaus:

while True:
		x = int(raw_input("Prashau ivesti skaichiu: "))
	except ValueError:
		print "Ivedei ne skaichiu, bandyk dar karta!"
	except (RuntimeError, TypeError, NameError):
		print "Ivyko siaubinga klaida!"
print "Ivedei skaichiu:", x

Exception'ai su klaidų numeriais ir aprašymais

Bandome atidaryti bylą ir perskaityti skaičių:

import sys
	byla = open ('/tmp/byla', 'r')
	eilute = byla.readline()
	skaichius = int(eilute.strip())
except IOError, (errno, strerror):
	print "I/O klaida nr. %s: %s" % (errno, strerror)
except ValueError:
	print "Pirmoje eiluteje nera skaichiaus!"
	print "Ivyko nenumatyta klaida: ", sys.exc_info()[0]
	# Mirshtam su visa klaida
# Vykdoma, jei neivyko klaidu
	print "Perskaichiau! Skaichius yra: ", skaichius

Savo exception'o kūrimas

# Kuriame savo exception'a
class GyvenimasBlogas (Exception):
	def __init__ (self, value):
		self.value = value
	def __str__ (self):
		return repr(self.value)
# Ji raise'iname
	raise GyvenimasBlogas ('Tai jau tikrai!')
except GyvenimasBlogas, argumentas:
	print "Gyvenimas blogas. ", argumentas.value

Klaidų exception'ai

# Klaidu exception'ai
class Error(Exception):
	"""Base class for exceptions in this module."""
class InputError(Error):
	"""Exception raised for errors in the input.
		expression -- input expression in which the error occurred
		message -- explanation of the error
	def __init__(self, expression, message):
		self.expression = expression
		self.message = message
class TransitionError(Error):
	"""Raised when an operation attempts a state transition that's not
		previous -- state at beginning of transition
		next -- attempted new state
		message -- explanation of why the specific transition is not allowed
	def __init__(self, previous, next, message):
		self.previous = previous
		self.next = next
		self.message = message

"finally" - išvalymo veiksmai

finally vykdomas nepriklausomai nuo to, ar pavyko įvykdyti tai, kas yra try statement'e, ar ne. Panaudotinas uždarinėjant naudotas bylas ir pan.

	raise KeyboardInterrupt
	print "Atia!"

"with" panaudojimas

:!: Nelabai veikia :-(

The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.

with open('/tmp/test1') as f:
	for line in f:
		print line

Exception'ai yra klasės

raise Class, instance


raise instance


raise instance.__class__, instance

A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around – an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order:

class B:
class C(B):
class D(C):
for c in [B, C, D]:
		raise c()
	except D:
		print "D"
	except C:
		print "C"
	except B:
		print "B"

Note that if the except clauses were reversed (with „except B“ first), it would have printed B, B, B – the first matching except clause is triggered.

This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information
Jei nenurodyta kitaip, šio wiki turinys ginamas tokia licencija: CC Attribution-Noncommercial-Share Alike 4.0 International
Recent changes RSS feed Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki