Print Error Type when I catch it

  • Permalink
  • submit to reddit
  • Email
  • Follow


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
Reply Jimbo 4/22/2010 11:50:30 PM

See related articles to this posting


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
Reply 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
Reply Steven 4/23/2010 3:33:35 AM
comp.lang.python 72696 articles. 12 followers. Post

2 Replies
217 Views

Similar Articles

[PageSpeed] 14


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

Catching print errors
Hello, I have written the following script to simulate write failure conditions in a real application. open(FILE, ">test.txt"); # # rm test.txt or chmod 000 test.txt, before the user gives input # my $input = <STDIN>; print FILE "Hello, World!\n" or die "Couldn't write to file: $!\n"; close (FILE); The problem is if I delete the file the program doesn't show any error msg and the file remains deleted. If I change the permissions to 000 the program is still able to write to file even though the permissions remain 000. ...

catch errors printing to a socket
I am using vfprintf to print to a smtp socket How do I catch an error if my smtp socket has been closed by the smtpd server On 12/06/2011 03:39 PM, Ramprasad Prasad wrote: > I am using vfprintf to print to a smtp socket > How do I catch an error if my smtp socket has been closed by the smtpd > server Ie. using a FILE* obtained through fdopen() ? "If an output error was encountered, these functions shall return a negative value." (<http://pubs.opengroup.org/onlinepubs/009695399/functions/vprintf.html>, <http://pubs.opengroup.org/onlinepubs/009695399/functions...

catching an error and printing stack trace
Hi, If I write code like the following, how can I print out the detailed stack trace, with line numbers etc. (i.e. what I would see if I never caught the error in the first place): try ... some code that throws an error ... catch display(lasterr); % this does not give a stack trace, just a message end TIA, Peter Peter Kalmus wrote: > > > Hi, > > If I write code like the following, how can I print out the > detailed > stack trace, with line numbers etc. (i.e. what I would see if I > never caught the error in the first place): > > try > ... some c...

How to catch 'error' type exceptions
Hi I am quite familiar with normal python errors which can be caught by using the try... except... finally clause. But very often I find other kinds of exceptions raised in my programs. Here is an example. <TRACEBACK> Traceback (most recent call last): File "D:\Python22\lib\threading.py", line 414, in __bootstrap self.run() File "WebUrlTracker.py", line 213, in run self.action() File "WebUrlTracker.py", line 207, in action self.downloadUrl() File "WebUrlTracker.py", line 249, in downloadUrl self.fetchUrl() File &quo...

Start-up error, as well as type 2 or -97 when printing.
Hi all I am posting the message on behalf of my aunt, as she treats me like the computer tech that I am not. Well in any event she is having a number of problems with her iMac. Below is the description of her computer and the problems she is encountering. My aunt is using an iMac 233mhz rev.B running on Mac 9.2 with 256mb of ram. Firstly she gets an error upon starting her computer about 40% of the time. This is a new one on me, as I think that I have only heard of this happening, but have never seen it. I know it is hard sometimes to pen point the exact problem from these postings, but wa...

How to catch 'extern' function return type error?
I ran into a nasty bug today that was caused by the return type of an 'extern' function being declared incorrectly. Apparently the compiler just trusts that you know what you're doing, and by the time the linker sees it the return type is gone. Here's an example: File1: #include <iostream> using std::cout; using std::endl; extern unsigned int badExtern(unsigned int i); void testExtern(unsigned int i) { cout << "badExtern(" << i << "): " << badExtern(i) << endl; } int main(int argc, char** argv) { testExtern(0);...

@@Error not catching error.
Hi all, I want to catch error in stored procedure and return error message. I want to catch error 'Syntax error converting the varchar value 'a' to a column of data type int.' Means error occuring if i enter wrong value. Say suppose i have statment like select * from emp where rowid = 'a' PRINT @@ERROR print 'reach' here rowid is integer value so i am getting above mention error. So what i am expecting is it should print error and then print 'reach' which is not happening. can anyone tell me reason behind this and how to overcome this problem. than...

OSX: Print
I have a rather annoying situation in OSX: Every time I try to print something, I get the usual progress indicator (printing page 1 etc), and then a info box that says: Print - error while printing. And no job shows up in the Print center for the particular printer. This happens in Safari (I reinstalled since I suspected it), iCal etc in MT-Newswatcher and Eudora I do not get the message box, but no job shows up either. Printing from Classic works. (Using 10.2.6, Tek740 Postscript printer) Any suggestions? TIA Marc -- Marc Heusser - Zurich, Switzerland Coaching - Consulting - Counsell...

Type I and type II error
Is there any matlab command to compute the type I and type2 error of two overlapped normal distributed functions. I know the means and stds for those two functions Thanks "Marco Wu" wrote in message <ikrig5$nrq$1@fred.mathworks.com>... > Is there any matlab command to compute the type I and type2 error of two overlapped normal distributed functions. > > I know the means and stds for those two functions > > Thanks Hi Marco, If you know the mean and standard deviations of the two Gaussians, then you know everything about those distributions since they are p...

Cups not printing from wine apps. error: lp: unable to print file: client-error-bad-request
When trying to print from wine apps to cups printer I get the error message below. I haven't seen this error message in this forum. Anything I can try? I have: Slackware 9.1 wine-2004040121 cups printer (HP2200 named it2200 on hp jetdirect) that prints from kde desktop apps and from command line (lp /etc/hosts and lpr /etc/hosts work) ..wine/config contains: [spooler] "FILE:" = "tmp.ps" "LPT1:" = "|lpr" "LPT2:" = "|gs -sDEVICE=bj200 -sOutputFile=/tmp/fred -q -" "LPT3:" = "/dev/lp3" ..win...

"Incompatible types" error though types are same generic type
Hello everyone,Even though two methods both use the generic return type - E - I'mgetting an error saying that they're incompatible types. Here's thetruncated code:public class CircularLinkedList<E> extends AbstractList<E> { private class Node { private E element; public E element () { return this.element; } } //end Node private class CircularLinkedIterator<E> implementsdataStructs.Iterator<E> { private Node current; public Node current () { return this.current; } public E get () {...

Error 0 occured at printing invoke node blb bla bla..., if I try to change the Postscript printing to bitmap printing using Options-printing menu.
Who might comment why I can not change the printing type without Error message in LV8.0.1. LV6.0 worked OK. Info: It is Russian locale system. BR Vladi &nbsp; ...

printing job completed no error but not printed
I am trying to print some files. I used lp command #lp -d sysout /etc/system request id(4) and then no printed job especially I go to text editor and I print that file Oka. The printing went Ok with the text editor but with the lp was issuing request ID with no output. Also #print /etc/system does not produce output and no error issued . Any Explainations ??? ...

Stopping ... ERROR: Errors printed on page ...
I created a program to lock a dataset, or sleep until it can be locked. Once a dataset has been locked then normal processing will continue on, so I don't want there to be any error messages related to the locks occurring. I have redirected the lock errors to another log, via proc printto, but there is an internal counter somewhere that is still causing the message at the very bottom of my log to say ERROR: Errors printed on page.... Is there a way to get this final error message to not occur in my log. Thanks, Woof Instead of executing the LOCK and testing success, execute something ...

Catching an error within an error block?
Hi, Is it possible to catch an error within an error processing block? Something like this: On Error GoTo errorBlock Dim l As Date l = "erty" exitBlock: Exit Sub errorBlock: On Error GoTo lastChance Dim k As Byte l = 90000000 Call GError.displayError(Err, "FMain.frm", "Command1_Click") Resume exitBlock lastChance: Call GError.displayError(Err, "Fmain.frm", "Command_click>>errorBlock") Resume exitBlock "Fernando Rodr�guez" <frr@fernando-rodriguez.com> wrote.....

Type 3 and Type 10 errors?????
Hi all I am posting this message, as my aunt is having some problems with her iMac computer. It all seemed to start about 1 1/2 weeks ago when she tried to print out an email (United Airlines itenerary) I sent her. She claims the computer froze up and she had to use a paper clip to restart it. Well in any event I was over there tonight trying to see if that was a one time thing or if it was a bigger problem. Seems to to be a much bigger problem. I say that as I got the following error messages this evening. -Claris Works 4.0 Type 3 error - I get this when trying to open up a new word proce...

type error resolving infix expression -- ERROR
hi friends, i have one type of signal that contains 64 values, each value of type integer range -128 to 128. signal named as ifftre. subtype addr is integer range 0 to 63. type samp of array(addr) is integer range -128 to 128. signal ifftre : samp; subtype addr1 is integer range 0 to 79; type samp1 of array(addr1) is integer range -128 to 128 signal cp : samp1; i got on output over that signal. then i want to get an another output of last 16 values with that of 64 values, total of 80 values i get and store it in another signal. for that i concatenate both values of same signal type cp <...

Error reading Excel sheet with #! type error
13 *-* Say '('iCol','iRow'):' myWorkSheet~Cells(iRow,iCol)~Value Error 92 running H:\My Documents\Source\ooRexx\tExcel.rex line 13: OLE error Error 92.902: Cannot convert OLE VARIANT to REXX object: The conversion of the VARIANT type VT_ERROR into a REXX object failed. Using oorexx 3.2.0 on XP with SP2, Excel 2003 with SP3. The cell in question has a simple #VALUE! error, but I'm not able to query it ahead of time to avoid this error, nor can I trap the error with any Signal/Call condition ("any" fails to trap it). There was a similar question here...

error: array type has incomplete element type ??
This is a part of the code : -------------------------------------------------------------- extern struct dummy temp[]; error: array type has incomplete element type -------------------------------------------------------------- which i compiled without any error on : $gcc -v Reading specs from /usr/bin/../lib/gcc-lib/powerpc-ibm-aix5.1.0.0 /2.9-aix51-020209/specs gcc version 2.9-aix51-020209 but the same code doesnt compile on the : $gcc -v Using built-in specs. Target: powerpc-ibm-aix5.3.0.0 Configured with: ../configure --with-as=/usr/bin/as --with-ld=/usr/bin/ ld --disable-nls --enab...

Turning off error notification for certain error types
I have error notification set for all my AIX servers to email me whenever there's a hardware error. Works great, except when my SAN guy is "doing stuff" with the SAN. Everything on the SAN is redundant, so he often takes one side down to do maintenance, then brings it back and does the same thing on the other side. Trouble is, when he does this, I get inundated with dozens of emails from all my SAN-attached servers. I'd like to be able to leave the hardware error notification on, but turn it off only for certain types of errors. I can't figure out what to put in the...

error 3464 Data type mismatch error!! ??
Does anyone know why I get the error 3464 Data type mismatch from the following code. I have a form with a combo(to choose a consumable) and 2 list boxes on it. list on left is all printers and list on right shows the ones currently compatible with the consumable chosen in the combo at the top. I want to add printers to a corresponding compatible consumable type, by clicking a button and it moving them from the left box to the right and putting the two values in a link table as it is a many 2 many. Now i can do this, but I also have a button which deletes the printers from the consumable b...

Type error when deriving new type from Num
Hi, I am creating a new type for algebra operations (Clifford Algebra, but rigth now it's only a simple type) I want to use (+), (*) ...etc operators. So I think that if a derived the new type from Num I will have the operators for free. This is the new type. I the future, when I have operators working, it'll be a full Multivector > data Multivector a = (Num a) => MV !a > instance Show (Multivector a) where > show (MV a) = show a With the Eq class there is no problem. > instance Eq (Multivector a) where > (MV x) == (MV y) = x == y And this is...

"There was an error printing the document..." error
At home There are 3 computers connected together via a DSL router / 4 port switch in a 'workgroup' arrangement all running at 100M/bit. 2 of the computers are running windows 2000 and the Laptop running Windows XP home. We have a HP 930c Ink jet printer and One of the Windows 2000 machines acting as a print server. Periodically when a family member goes to print over the network, either from the Other win2000 machine or the Laptop running Windows XP home, the following message will frequently appear on the Print Server workstation. http://alpinedragon.orcon.net.nz...

Error Code: 33 [ DATA TYPE ERROR ]
Hope all well. Using VO 2.8 - 2837. Could anyone (Robert if you are there) can shed some light on the cause of Error Code: 33 [ DATA TYPE ERROR ] ? This occurs on various sites, but I cannot duplicate the issue my system and I do a remote web session, I still could not duplicate with the customer tracing the sequence of operations. The VOERROR.LOG has an error on a line: LOCAL dEndDate AS DATE dEndDate := SELF:oDCmDropdate:Value // ERROR 33 HERE . oDCmDropdate is DateTimePicker control which exists on a data window. Error Object created: ----------------...