Print Error Type when I catch it

Hello

I have a relatively simple question. I want to use a try except in a
function & when an error occurs I want to print the error type name(eg
IOError, OSError etc) do you know how I can do this without specifying
all possible errors, eg having to do this "except (IOError, OSError,
IndexError, ....):"

try:

    ... some code

except:
     # Here I want to print type of error that occured
     print errorType

The reason I want to do this is because one of my complex programs is
crashing BUT no python error message is comming up in red when I run
it, so I cant figure out what error occured? So I think its time I
learnt to print out my own errors & their types
0
Jimbo
4/22/2010 11:50:30 PM
comp.lang.python 74911 articles. 0 followers. Post Follow

2 Replies
332 Views

Similar Articles

[PageSpeed] 5
On Thu, Apr 22, 2010 at 4:50 PM, Jimbo <nilly16@yahoo.com> wrote:
> I have a relatively simple question. I want to use a try except in a
> function & when an error occurs I want to print the error type name(eg
> IOError, OSError etc) do you know how I can do this without specifying
> all possible errors, eg having to do this "except (IOError, OSError,
> IndexError, ....):"
>
> try:
>
> =C2=A0 =C2=A0... some code
>
> except:
> =C2=A0 =C2=A0 # Here I want to print type of error that occured
> =C2=A0 =C2=A0 print errorType
>
> The reason I want to do this is because one of my complex programs is
> crashing BUT no python error message is comming up in red when I run
> it, so I cant figure out what error occured? So I think its time I
> learnt to print out my own errors & their types

try:
    # code
except Exception as exc:
    print type(exc).__name__

Cheers,
Chris
--
http://blog.rebertia.com
0
Chris
4/23/2010 12:07:51 AM
On Thu, 22 Apr 2010 16:50:30 -0700, Jimbo wrote:

> Hello
> 
> I have a relatively simple question. I want to use a try except in a
> function & when an error occurs I want to print the error type name(eg
> IOError, OSError etc) do you know how I can do this without specifying
> all possible errors, eg having to do this "except (IOError, OSError,
> IndexError, ....):"
> 
> try:
> 
>     ... some code
> 
> except:
>      # Here I want to print type of error that occured print errorType

As a general rule, bare excepts are terrible practice and should be 
avoided.

At most, you should write:


try:
    ...
except Exception:
    ...

which will allow keyboard interrupts to continue to work correctly.

In Python 2.5 or 2.6, you can say:

try:
    ...
except Exception, e:
    print e  # prints the exception object
    print type(e)  # prints the type of exception
    print type(e).__name__  # prints the type's name
    raise  # re-raise the error and get a traceback

In Python 2.6 you can also use

except Exception as e:

and in 3.x you *must* use the "as e" form.


> The reason I want to do this is because one of my complex programs is
> crashing 

Perhaps you should aim to make them less complex? *wink*


> BUT no python error message is comming up in red when I run it,

What do you mean, "crashing"? If you're not getting an exception raised, 
and a printed traceback, how do you know it is crashing?

Do you mean it is dumping core? If so, then a try...except won't save you.


> so I cant figure out what error occured? So I think its time I learnt to
> print out my own errors & their types

The best way to print out errors is:

DO ABSOLUTELY NOTHING.

Python will automatically print out the errors, unless you suppress them 
with a try...except. So stop suppressing them and let Python do what it 
is supposed to do!


-- 
Steven
0
Steven
4/23/2010 3:33:35 AM
Reply:
Similar Artilces:

JDBC-ODBC, ERROR
I just upgraded to Tomcat 4.1.29 and I am receiving the following error when I connect via ODBC to an oracle database: java.lang.ClassNotFoundException: Security Violation, attempt to use Restricted Class: sun.jdbc.odbc.JdbcOdbcDriver This is a JSP application (NOT an applet). Does anyone have any idea's what I need to do to fix this? Thanks in advance :) ...

How to print permutations?
If we have three variables a,b,c...which are char variables....then hoe to print there all permutations? for example....abc, bac, cab.......all of them.... Shraddha wrote: > If we have three variables a,b,c...which are char variables....then > hoe to print there all permutations? > for example....abc, bac, cab.......all of them.... > Are all of these questions school work or something? On 25 Maj, 14:44, Shraddha <shraddhajosh...@gmail.com> wrote: > If we have three variables a,b,c...which are char variables....then > hoe to print there all permutations? > for ex...

Errors in Windows 7
Hello We are running our database update program at a customers and we are getting errors. dbFileSpec:Create is returning false, but the file does appear to be created as the file is opened, and has the new correct structure. There are no errors in it, but it still reports as an error. Windows 7 W/S ADS 9.1 Could this be rights or client issue? How does :Create() know if it has creted the file? Thanks Martin More likely to be a rights issue. Check user account control or run the application as Administrator. You have to remember that W7 is basically Vist...

print math symbol into image created with GD
Hy! I am using the GD::Simple libs to draw a simple diagram. My problem is, that I have to put some math symbols in there (for example the symbol for delta and my). Is there an easy way to do that? Best regards, Kai Kai Schlamp schreef: > I am using the GD::Simple libs to draw a simple diagram. My problem > is, that I have to put some math symbols in there (for example the > symbol for delta and my). > Is there an easy way to do that? Yes, with a proper font. -- Affijn, Ruud "Gewoon is een tijger." Yep ... figured it out ... used a truetype font named symbol.tt...

Color Printing
Is there any other color printer I can use with the IIGS other than the Imagewriter II? I read through the FAQs and didn't see anything other than the Epson LQ mentioned. Is there anything else I can use? A Color Stylewriter, perhaps? Pat Patricia Glenn wrote: > Is there any other color printer I can use with the IIGS other than the > Imagewriter II? I read through the FAQs and didn't see anything other than > the Epson LQ mentioned. Is there anything else I can use? A Color > Stylewriter, perhaps? > > Pat I had my Epson Color Stylus 800 colour inkjet printe...

read file and print contents
hello, im new to ruby and i have a text file and want to read in the file and print it out. so far iv got the following. I'd greatly appreciate any help. thanks. text file (reference.txt): Tag: ref1 Type: Book Author: Little, S R ruby file: #!/usr/local/bin/ruby # # # read file and print # ARGV.each do |fn| begin (fn == '-' ? STDIN : File.open(fn)).each_line do |l| if $indent > 0 (1..$indent).each { print ' ' } end puts l end -- Posted via http://www.ruby-forum.com/. I would change if $indent > 0 (1..$indent).each { print ...

Round-off error?
Hi everyone, The following lines of code are stumping me. ClearAll[y] dt = 0.15; Do[y[i*dt] = "hi there", {i, 0, 20}] Table[{i, y[(i + 1)*dt], y[i*dt + dt]}, {i, 0, 19}] Here is the output: 0 hi there hi there 1 hi there hi there 2 hi there hi there 3 hi there hi there 4 hi there hi there 5 hi there y(0.9) 6 hi there y(1.05) 7 hi there hi there 8 hi there hi there 9 hi there hi there 10 hi there hi there 11 hi there hi there 12 hi there y(1.95) 13 hi there hi there 14 hi there hi there 15 hi there hi there 16 hi there hi there 17 hi there hi there 18 ...

Re: help with print/page #3
tomarsin2015@comcast.net wrote on 03/03/2006 12:28:27 PM: > Thanks for replies. > AFRICA> sqf laserjet5l > Printer queue LASERJET5l, idle, on AFRICA::"10.120.201.200:9100", > mounted form DEFAULT > <laserjet 5l> > /BASE_PRIORITY=4 /DEFAULT=(FEED,FORM=DEFAULT) Lowercase > /OWNER=[SYSTEM] > /PROCESSOR=TCPIP$TELNETSYM /PROTECTION=(S:M,O:D,G:R,W:S) > > Entry Jobname Username Blocks Status > ----- ------- -------- ------ ------ > 103 TAPE0909 SYSTEM 3139 Holding > Submitt...

Re: error with saspora
I guess that this error is with the Oracle client and S.O variables. Which are the contents of LD_LIBRARY_PATH ? Coult you compare this with the same user used in "D.I Studio" ? Did you have access to Metalink ? Att: Paulo R. Herculano SAS Consultant +55-11-9226 6618 Sk=E5l Thunar!! On Fri, Sep 19, 2008 at 6:35 AM, Aamodt <vicente.bruno@gmail.com> wrote: > Hi, when I try to run this .bat > > DATA_ACTUAL=3D`date '+%Y%m%d'` > /usr/local/sas9/SAS_9.1/sas -autoexec '/home/sasadm3/sasadm/ > WebReportsPPHist/Source/autoexec_sasapli.sas9' -config '...

Expression Error
Have a runtime error 'Expression Error, subscript range, 101' in a program printing client statements - appears may be due to a corrupt client record... any pointers? -- Donald Leask Dear Donald Leask: On Nov 21, 7:26 am, "Donald Leask" <d...@mweb.co.za> wrote: > Have a runtime error 'Expression Error, subscript range, > 101' in a program printing client statements - appears > may be due to a corrupt client record... any pointers? Very little generic advice. Presumably you tried rebuilding the indexes? When you say you are "printing clie...

Hiding 5333 error on closing the program
In quite some cases, my program(s) end with the following error: Error Code: 50 [ ] Subsystem: VO-CODE Error Subcode: 5333 Argument Number: 2 There are usually no callstack program lines in the log and if there are, they are of little use with 5333 errors. We have found no cause and we can not reproduce it to rule out the use of certain program points. It seems that the error comes up pretty random. Although such an error on closing is harmless, it looks a bit sloppy <g> and I wonder if there's any way to catch this error somewhere in an errorhandler, just to hide ...

I wanna to print two copies of a print job from two different trays
Hi , I have a very critical printing incidence, At one of my customer's premises, we need to print two copies of every invoice, and we need to direct each copy to different tray of the HP 4250tn printer. Can your know a software that has a feature to avail it? Please guide ASAP IF YOU HAVE TO POST THAT YOU GOOTA BE REAL DUMB mannubhai wrote: >Hi , >I have a very critical printing incidence, >At one of my customer's premises, we need to print two copies of >every invoice, and we need to direct each copy to different tray of the > >HP 4250tn pri...

Trouble Printing Yellow On HP R80xi+
I have a 3 year old HP Multifunction R80xi ink jet printer that I have probably printed a total of 2,500 pages on. For some reason I can not get it to print yellow. I have installed brand new ink cartridges (both black and color) and have cleaned, calibrated, and done everything else I can think of. Also have searched HP's site for help. I am running 98SE. Can anybody give some guidance? -- <Bill> Brought to you from beautiful Unalaska/Dutch Harbor, Alaska. N 53� 51.140' W 166� 30.228' (WGS 84) ...

Strange Out of memory error.
Hi, Below is shown a simplified version of a construct I have been used for years without any problem, but now it produce an error 7(Out of memory). What's new lately is that I have upgraded my memory from 1 to 2GB, and upgraded Windows XP from SP2 to SP3. Have anyone experienced memory problem with WinXP SP3? I tried making the array global, but that didn't make any difference. -- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////...

how to print document generated by man?
On Wed, 4 Aug 2004 19:57:24 +0300, serg wrote: Please bookmark the following, very large, Frequently Asked Questions (faq) Search engine: http://groups.google.com/advanced_group_search print man document in the first box *unix* in Newsgroup, U need 2 use *, pick English Results 1 - 10 of about 3,580 for print man document group:*unix*. (1.41 seconds) In article <cer4oe$2bm$1@snake.ukrnet.net>, serg <serg@sigma.icmp.lviv.ua> wrote: > > > man command | col -b Chuck Demas -- Eat Healthy | _ _ | Nothing would be done at all, Stay Fit ...

Error message using "Copy Database Wizard"
Any advice from the crowd? Every time I try to run "Copy Database Wizard" I get an error message saying I must be a member of the sysadmin group and have permission to copy files over the network. I'm a local admin on both boxes and a member of the sysadmin group on both SQL servers and an admin on the network. What am I missing here? Thanks, Ralph Noble ralph_noble@hotmail.com Is the target server running under a domain account? Check out: http://support.microsoft.com/default.aspx?scid=kb;en-us;274463&Product=sql -- Hope this helps. Dan Guzman SQL Server MVP "R...

How to input strings of any lengths into arrays of type: char *array[SIZE] ?
hey everyone! i have this little problem. consider the following declaration: char *array[4] = {"wilson", "string of any size", "etc", "input"}; this is a common data structure used to store strings of any lengths into an array of pointers to char type variable. my problem is: given the declaration char *array[SIZE]; how to store strings of any length into this array from the user input using functions like "scanf", "gets" etc. ? let me know if you get it! -thanks, arko arkobose@gmail.com wrote: > hey everyone!...

The Microsoft Jet database engine stopped the process because you and another user are attempting to change the same data at the same time. (Error 3197)
I have a main form and a subform (linked) with a delete button on the main form When the users fill out the fields on the main form and click the delete button--> but when prompted to delete, the user does not delete......then goes on to fill out the subform....I get a The Microsoft Jet database engine stopped the process because you and another user are attempting to change the same data at the same time. (Error 3197) I don't understand why???????/ On Mar 3, 9:52=A0am, audrey....@gmail.com wrote: > I have a main form and a subform (linked) with a delete button on the > main fo...

more than one print to a page
I suspect this is a basic question, but I would appreciate help. How do I place multiple images on one page to be printed? I guess it comes down to, how do I add a second image to a page to be printed? Thanks. Bob On Sat, 12 Jan 2008 11:49:40 -0500, "robertmcdonaldph" <robertmcdonaldph@bellsouth.net> wrote: >I suspect this is a basic question, but I would appreciate help. How do I >place multiple images on one page to be printed? I guess it comes down to, >how do I add a second image to a page to be printed? > >Thanks. > >Bob > Are you usin...

Printing problems
Hi all. I'm running MacOS X 10.3.5 on a G4 iMac. My printer is an HP LaserJet 3330mfp, connected via the USB port. Yesterday, printing stopped working. The connectivity is OK; System Profiler can find the printer. Just for fun, I tried updating the printer driver software, which was at version 4.0.9. Going to the HP website, I found that the software is currently at version 5.9.5. After the update, I found that I could print, but my wife (the other user of this machine) cannot. Any print job she sends out hangs indefinitely in the queue. Furthermore, once she attempts to print, ...

How print pdf file without Acrobat Reader ?
Hello I've created a pdf file with ItextSharp. How can I print this file without Acrobat Reader ? Is it possible ? Thanks Olivier "Olivier" <aa@aa.aa> wrote: >I've created a pdf file ... >How can I print this file without Acrobat Reader ? By using a different tool that reads PDF and can print it to your printer (e.g. GhostScript); or by sending it to one of the (very few) printers that understand PDF. ---------------------------------------- Aandi Inston quite@dial.pipex.com http://www.quite.com Please support usenet! Post replies and follow-ups, don&#...

Printing and saving figures
Hello everyone, Im having trouble saving figures that i plot in Scilab 3.0. A line always comes up saying that the new plot saving format is not available. Is this an error on my part during installation, or a bug? I'm running on Windows 2000. Thank you! ...

Error message when I open Foxit reader with TeXnicCenter?
I use TeXnicCenter, MikTex compiler. I use to open the pdf files with Foxit Center instead of Acrobat Reader. The reason is that Acrobat Reader slows down my computer. So, I create a file in TeXnic, but there's a difficulty. I went to Profiles-->Viewer and I changed the path from Acrobat to Foxit.exe When I try to view the file, Foxit shows a message, "open the file". I open it and can view the file. But I get a message DocOpen("%bm.pdf")][FileOpen("%bm.pdf")] cannot execute the command. I add that this DDE command is under view object's output , ser...

Error Cannot read from file?
This is my first post to this group, I hope some one can help. I have upgraded two of my boxes to W2K Pro. (previously WIN98SE.) Two others are still on WIN98SE. Now the problem! Some images I created with P.S.P.6 on my main box while running WIN98 ( 3 G Hz . 512 Ram.) will not open with W2K Pro. (not enough memory/cannot read from file, not allways the same). The other box with W2K will open the same file from the same location (via LAN) One box (WIN98, 70Hz, 256Meg memory) has no problems with the same file from the same location. The forth box is even an slower computer, and that has n...

Re: HP 5170
Please ignore this one - have reposted - got printer no wrong in subject "Chris B" <chris.brogan@thefreeinternet.co.uk> wrote in message news:... > I do not have the option to print on 5 x 7 paper on my print menu. > > I want to print colour photos to this size paper. > > Any idea how I can resolve this? > > Many thanks > > Chris > > ...