473,796 Members | 2,788 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Questions on exceptions

Hi everyone,

I've just finished studying O'Reilly's "Learning python" and since I
come from the Java world, there are some things that bother me
concerning python's exception handling.

In Java, all methods must declare the exceptions throwed (I'm speaking
of checked exceptions)... but this is not the case in Python. So my
question is : how can I know which exceptions I must catch ? (am I
supposed to believe what's written in the documentation ? am I supposed
to read the source code to see which exceptions are throwed ?)

Also, can someone explain me why there is no try...except... finally
statement ? For example, the following code snippet is not valid, but
what would be the correct python way to do it ?

myFile = open('file.txt' ) # assume file exists
try:
for nextLine in file:
nextLine = nextLine.rstrip ('\n');print "line = " + nextLine
except IOError:
print "Error while reading from file"
finally:
myFile.close

Aug 21 '06 #1
2 1488
In <11************ **********@i3g2 000cwc.googlegr oups.com>, sc_wizard29
wrote:
Also, can someone explain me why there is no try...except... finally
statement ?
AFAIK historical reasons. There where some concerns about ambiguity. But
in Python 2.5 this form will become legal syntax.
For example, the following code snippet is not valid, but
what would be the correct python way to do it ?

myFile = open('file.txt' ) # assume file exists
try:
for nextLine in file:
nextLine = nextLine.rstrip ('\n');print "line = " + nextLine
except IOError:
print "Error while reading from file"
finally:
myFile.close
You forgot the parenthesis for the `close()` method.

In Python <=2.4 you have to nest:

try:
try:
pass
except Error:
pass
finally:
pass

Maybe you are interested in the new (Python 2.5) ``with`` statement too:

http://docs.python.org/dev/ref/with.html

And the style guide: http://www.python.org/dev/peps/pep-0008/ (because you
used Java naming conventions)

Ciao,
Marc 'BlackJack' Rintsch
Aug 21 '06 #2
On Mon, 21 Aug 2006 00:40:14 -0700, sc_wizard29 wrote:
Hi everyone,

I've just finished studying O'Reilly's "Learning python" and since I
come from the Java world, there are some things that bother me
concerning python's exception handling.

In Java, all methods must declare the exceptions throwed (I'm speaking
of checked exceptions)... but this is not the case in Python. So my
question is : how can I know which exceptions I must catch ? (am I
supposed to believe what's written in the documentation ? am I supposed
to read the source code to see which exceptions are throwed ?)
How do you know what objects a method will return? Are you supposed to
believe the documentation? Are you supposed to read the source code?

Exceptions are no different. If a method claims to raise ValueError, but
sometimes raises TypeError, I call that a bug, regardless of whether the
line which causes it is "int(x) + str(y)" or "raise TypeError('My
documentation is incomplete')".

Also, can someone explain me why there is no try...except... finally
statement ?
Historical reasons. I believe that Python 2.5 will support it.
For example, the following code snippet is not valid, but
what would be the correct python way to do it ?

myFile = open('file.txt' ) # assume file exists
try:
for nextLine in file:
nextLine = nextLine.rstrip ('\n');print "line = " + nextLine
except IOError:
print "Error while reading from file"
finally:
myFile.close
Nested try...except blocks.
--
Steven D'Aprano

Aug 21 '06 #3

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

Similar topics

1
4231
by: Old Wolf | last post by:
1. What is the difference between #include <stdexcept> and #include <exception> ? 2. Is there a list somewhere of what each standard exception is used for? either to throw them, or throw user-defined exceptions derived from them? (for example I have been deriving mine from std::bad_alloc if there was a memory problem, or std::bad_exception if there was some other problem) 3. Is it a good idea to make all user-defined exceptions derive...
3
1919
by: Gonçalo Rodrigues | last post by:
Hi all, I've got two somewhat general questions related to exception handling in C++. My usual programming language is the lovely and flexible Python, but for various reasons, including the need to interface with third-party libraries, get extra performance, etc. I have to use C++. Now in Python, being a dynamically typed language, everything is pushed to the run-time. Additionaly, since the language does not guarantee deterministic...
3
1133
by: Paul | last post by:
In general how do you indentify a specific error? If 2 different error conditions throw the same type of exception how do you know which error occured? There are no error numbers, so are you forced to compare Message strings? But these strings are locale dependent, so that wouldn't work. Also, is there a complete table or listing of possible framework errors? I've never seen one.
11
1964
by: Lloyd Dupont | last post by:
(not I use 2.0, so new return a "normal" pointer and gcnew return a managed one, my question below regarding new concern plain standart C++ allocator) - if I use the default new operator, are all the instance variable initialize to NULL / 0 ? - if there is not enough memory what happend with new ? does it return NULL or throw an exception? - if new throw a native C++ exception what happen in Managed C++ ?! - if there is an exception in...
4
1855
by: Steve | last post by:
I have read a couple articles online, read my Jesse Liberty book but I am still confused as to just what the best practices are for using exceptions. I keep changing how I'm working with them and it has now, after 15k lines of code resulted in a royal mess! It's my hope to ask some specific questions with scenario examples and that some of you might offer a little guidance or general suggestions. 1) string...
2
1205
by: pack | last post by:
"Unless you have a very good reason to catch an exception, DON'T. Exceptions are supposed to be exceptional, just like the dictionary meaning: uncommon, unusual. When in doubt, let the calling routine, or the global exception handler, deal with it. This is the golden rule. The hardest kinds of exceptions to troubleshoot are the ones that don't even exist, because a developer upstream of you decided to consume it." What's "global...
33
2062
by: john | last post by:
I am reading TC++PL3 and in "21.3.3 Stream State", 4 member functions returning bool are mentioned: template <class Ch, class Tr= char_traits<Ch class basic_ios: public ios_base { public: // ... bool good() const; // next operation might succeed bool eof() const; // end of input seen
5
1723
by: Soumen | last post by:
For one of my project, I want to use auto_ptr. But I'm facing few issues. 1. Say I've Controller class. I don't want to allow user to create object of this class unless all arguments are valid. So I've made the constructor private and given one static method to create an object of this class. Since one of senior members in the team doesn't like throwing exception, I've made this static method to return NULL pointer when arguments are...
2
1013
by: skanemupp | last post by:
is there a general philosophy as to when to use exceptions and when not to? like here: def Calc(): global nbr try: print eval(nbr) except: print "Not computable"
0
9685
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
10239
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10190
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10019
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
7555
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
6796
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
5447
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
4122
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
3736
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.