473,799 Members | 3,218 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

forcing exceptions

Is there a way to tell the interpreter to display exceptions, even those
which were captured with except?

--
"Now the storm has passed over me
I'm left to drift on a dead calm sea
And watch her forever through the cracks in the beams
Nailed across the doorways of the bedrooms of my dreams"
Mar 3 '06 #1
5 1281
Nikola Skoric <ni*******@net4 u.hr> writes:
Is there a way to tell the interpreter to display exceptions, even those
which were captured with except?


Normally you wouldn't do that unless you were trying to debug the
interpreter itself. It uses caught exceptions for all sorts of things
that you probably don't want displayed. I think even ordinary loop
termination may be implemented using exceptions.
Mar 3 '06 #2
Nikola Skoric wrote:
Is there a way to tell the interpreter to display exceptions, even those
which were captured with except?

Yes, sort of ... You have to trigger the display yourself within the
capturing "except" -- it's not automatic.

The traceback module provides a number of functions that can be used to
display a traceback of the current (or any other) exception. In
addition, it can produce a traceback of the current state of the
execution stack even without an exception:

Example (type this into the Python interpreter):

import traceback
try:
assert False
except:
traceback.print _exc()

and you'll get a traceback (a very short one in this case):

Traceback (most recent call last):
File "<stdin>", line 2, in ?
AssertionError

Gary Herron
Mar 3 '06 #3
In article <7x************ @ruckus.brouhah a.com>, Paul Rubin
<http://ph****@NOSPAM.i nvalid> says...
Nikola Skoric <ni*******@net4 u.hr> writes:
Is there a way to tell the interpreter to display exceptions, even those
which were captured with except?


Normally you wouldn't do that unless you were trying to debug the
interpreter itself. It uses caught exceptions for all sorts of things
that you probably don't want displayed. I think even ordinary loop
termination may be implemented using exceptions.


Yes, thanks for your quick responses, all three. You're right, I don't
want to debug python :-) But I figured out that I don't need captured
exceptions, the thing is that I just didn't belive the problem was that
obvious. In fact, problem was in the except block, not in it's try
block. The except block had this inocent statement:

print self.sect[1].encode('utf-8')

Which results in:

Traceback (most recent call last):
File "AIDbot2.py ", line 238, in ?
bot.checkNomina tions()
File "AIDbot2.py ", line 201, in checkNomination s
if sect.parseSect( ) == 1:
File "AIDbot2.py ", line 96, in parseSect
print self.sect[1].encode('utf-8')
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xfc in position 15:
ordinal
not in range(128)

Now, who can it complain about 'ascii' when I said loud and clear I want
it to encode the string to 'utf-8'??? Damn unicode.

--
"Now the storm has passed over me
I'm left to drift on a dead calm sea
And watch her forever through the cracks in the beams
Nailed across the doorways of the bedrooms of my dreams"
Mar 3 '06 #4
Nikola Skoric wrote:
print self.sect[1].encode('utf-8')

Which results in:

Traceback (most recent call last):
File*"AIDbot2.p y",*line*238,*i n*?
bot.checkNomina tions()
File*"AIDbot2.p y",*line*201,*i n*checkNominati ons
if*sect.parseSe ct()*==*1:
File*"AIDbot2.p y",*line*96,*in *parseSect
print*self.sect[1].encode('utf-8')
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xfc in position 15:
ordinal
not*in*range(12 8)

Now, who can it complain about 'ascii' when I said loud and clear I want
it to encode the string to 'utf-8'??? Damn unicode.


Trying to encode a str s results in something like

unicode(s, "ascii").encode ("utf-8")

where the first step, i. e. the conversion to unicode fails for non-ascii
strings. The solution is to make that conversion explicit and provide the
proper encoding. Assuming the initial string is in latin1:

unicode(self.se ct[1], "latin1").encod e("utf-8")

Of course, if you can ensure that self.sect[1] is a unicode instance earlier
in your code, that would be preferable.

Peter
Mar 3 '06 #5
Nikola Skoric wrote:
Traceback (most recent call last):
File "AIDbot2.py ", line 238, in ?
bot.checkNomina tions()
File "AIDbot2.py ", line 201, in checkNomination s
if sect.parseSect( ) == 1:
File "AIDbot2.py ", line 96, in parseSect
print self.sect[1].encode('utf-8')
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xfc in position 15:
ordinal
not in range(128)

Now, who can it complain about 'ascii' when I said loud and clear I want
it to encode the string to 'utf-8'??? Damn unicode.


Presumably, self.sect[1] is not a unicode string, but a regular string. The
utf-8 encoder only takes unicode strings, so it tries to convert the input into
a unicode string first. ASCII is the default encoding when no encoding is specified.

Standard practice with unicode is to only do conversions at the boundaries
between your code and interfaces that really need bytes (files, the console, the
network, etc.). Convert to unicode strings as soon you get the data and only
convert to regular strings when you have to. Everything *inside* your code
should be unicode strings, and you shouldn't try to pass around encoded regular
strings if at all possible, although pure ASCII strings generally work because
it is the default encoding.

So double-check self.sect[1] and figure out why it isn't a unicode string.

--
Robert Kern
ro*********@gma il.com

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Mar 3 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
5295
by: David Turner | last post by:
Hi all I noticed something interesting while testing some RAII concepts ported from C++ in Python. I haven't managed to find any information about it on the web, hence this post. The problem is that when an exception is raised, the destruction of locals appears to be deferred to program exit. Am I missing something? Is this behaviour by design? If so, is there any reason for it? The only rationale I can think of is to speed up...
12
3699
by: Ritz, Bruno | last post by:
hi in java i found that when a method has a throws clause in the definition, callers must either handle the exceptions thrown by the method they are calling or "forward" the exception to the caller by specifying a throws clause as well. is there a similar machanism in c++? i want to force a developer to write handlers for all possible exceptions a method of my class library can throw.
17
3148
by: Bryan Bullard | last post by:
hi, is there a way to force the user of an object to catch exceptions of specific type? for instance a compile error is issued if exception 'ExeceptionXXX' thrown by method 'ThrowsExceptionXXX' is not caught. thanks,
40
3059
by: Neo The One | last post by:
I think C# is forcing us to write more code by enforcing a rule that can be summarized as 'A local variable must be assgined *explicitly* before reading its value.' If you are interested in what I mean, please look at this feedback my me: http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=3074c204-04e4-4383-9dd2-d266472a84ac If you think I am right, please vote for this feedback.
2
2640
by: AC [MVP MCMS] | last post by:
Having a heck of a time trying to create a ton of AD user accounts in a specific OU without having the users be forced to change their password upon a successful login. After creating the account (and committing the changes), I have the following code that works: // password info userEntry.Invoke("SetPassword", new object{this.m_defaultPassword}); userEntry.Properties.Value = 0; userEntry.Properties.Value = 0x200; ...
9
9647
by: Joel Byrd | last post by:
I've got a div whose width is specified as a percentage so that if you shrink the browser window, the div shrinks, and the text inside the div wraps around to accommadate this. The problem is: if I put a really long word (like a web address) in the div, then it props the rest of the text open to the width of the word, and the text can't wrap past that width; but if I shrink the browser window, the div also shrinks and so the net result...
1
2392
by: Anonieko | last post by:
Understanding and Using Exceptions (this is a really long post...only read it if you (a) don't know what try/catch is OR (b) actually write catch(Exception ex) or catch{ }) The first thing I look for when evaluating someone's code is a try/catch block. While it isn't a perfect indicator, exception handling is one of the few things that quickly speak about the quality of code. Within seconds you might discover that the code author...
2
1029
by: Steve | last post by:
Hi, Is their any way to setup VS such that it forces programmers to handle all exception (similar to Java). Thanks --
0
6505
RedSon
by: RedSon | last post by:
Chapter 3: What are the most common Exceptions and what do they mean? As we saw in the last chapter, there isn't only the standard Exception, but you also get special exceptions like NullPointerException or ArrayIndexOutOfBoundsException. All of these extend the basic class Exception. In general, you can sort Exceptions into two groups: Checked and unchecked Exceptions. Checked Exceptions are checked by the compiler at compilation time. Most...
0
9688
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10490
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10030
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7570
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6809
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5467
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4146
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3762
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.