Turinys

Klaidos (exception'ai)

Exception'o pavyzdys

Prašome skaičiaus:

while True:
	try:
		x = int(raw_input("Prashau ivesti skaichiu: "))
		break
	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
 
try:
	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!"
except:
	print "Ivyko nenumatyta klaida: ", sys.exc_info()[0]
 
	# Mirshtam su visa klaida
	raise
 
# Vykdoma, jei neivyko klaidu
else:
	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
try:
	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."""
	pass
 
class InputError(Error):
	"""Exception raised for errors in the input.
 
	Attributes:
		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
	allowed.
 
	Attributes:
		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.

try:
	raise KeyboardInterrupt
finally:
	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

arba

raise instance

arba

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:
	pass
class C(B):
	pass
class D(C):
	pass
 
for c in [B, C, D]:
	try:
		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.