473,703 Members | 4,129 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help needed: try/except -idiom vs. C-style coding

Hi there,

I have defined function that calls another functions like this
(modified for this mail):

def main_function() :
if not function1():
m = "main_funct ion: function1 failed"
print_error(m)
return False
if not function2():
m = "main_funct ion: function2 failed"
print_error(m)
return False
if not function3():
m = "main_funct ion: function3 failed"
print_error(m)
return False
return True

In book "Learning Python 1st edition" is was said
that this C-style programming is bad practice
and should be replaced with structure:

def main_function() :
try:
function1():
function2():
function3():
except:
what_ever()
return False (?)
else:
return True (?)

How can I use try/except -style if I want to know WHICH
of functions 1-3 failed in try: -section and print
that information? What should functions return in order to
a) raise an exception and
b) tell main_function "it was me who failed for this reason"
This message should be user specific.

Note that main_function might also be subroutine and must
information of its failure to its upper level.

I am looking something like:

def main_function() :
try:
function1():
function2():
function3():
except: !!!! FIX !!!!!
print "Function %s failed in main_function" % functions_name print
"Reason: %s" % functions_error _message

Does try/except -idiom expect that message
'"print "Reason: %s" % functions_error _message'
is always printed at the function itself, not by
its caller's except : -section?

-pekka-
Jul 18 '05 #1
1 1112
pekka niiranen wrote:
How can I use try/except -style if I want to know WHICH
of functions 1-3 failed in try: -section and print
that information? What should functions return in order to
a) raise an exception and
b) tell main_function "it was me who failed for this reason"
This message should be user specific.


If you feel you *must* print the name of the function that failed then you
can extract it from the traceback object:
import sys, traceback
def function1(): pass def function2(): raise RuntimeError('o ops') def function3(): pass def main(): try:
function1()
function2()
function3()
except RuntimeError:
type, value, tb = sys.exc_info()
filename, lineno, functionname, text = traceback.extra ct_tb(tb)[-1]
print functionname

main() function2

A more usual way to handle this would be to just print a traceback. That
way the user gets not only the information about the function that threw
the exception, but also the route that led to that function.
def main(): try:
function1()
function2()
function3()
except RuntimeError:
traceback.print _exc()
main()

Traceback (most recent call last):
File "<pyshell#5 0>", line 4, in main
File "<pyshell#4 4>", line 1, in function2
RuntimeError: oops
Jul 18 '05 #2

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

Similar topics

6
2966
by: Sims | last post by:
Hi, Given a string $txt and an array of strings $txt_array what would be the best/fastest way to search in _insensitive_ case if $txt is in $text_array and, if it is, where is it? Because I want to use the array with an ID Something like,
6
2671
by: Jack Smith | last post by:
Help needed on this question. Any help is appreciated. Thanks in advance. Given a binary string (i.e. a finite sequence of 0's and 1's) we choose any two digit substring 01 and replace it by a string of the form 100...0 using an arbitrary (but finite) number of zeros. Prove by induction that this transformation can not be performed infinitely many times, i.e. this sequence of transformations must terminate for any input string.
1
1977
by: worzel | last post by:
Hi All, I am looking for a reg ex that will match email addresses withing <a href=mailto blah > links. Actually, I already crafted my own, but with a slight problem: <a href="mailto:fred@blah.com"> emal me</a> woud be matched as expected, but so will:
2
1484
by: Willie | last post by:
I try to setup SQL Server to work with .NET Framework Anyone here willing to help? Step By Step Help Needed. Thanks
14
2181
by: tbird2340 | last post by:
I want to write an if / then statement and have tried using this: var MyVarMailto; if (Request.Form("LoanRequest") == "Under $250,000") { if (Request.Form("Organization") == "1") { MyVarMailto = "emailA@address.com"; } } else if (Request.Form("LoanRequest") == "Over $250,000") { if (Request.Form("Organization") == "1") {
1
1736
by: BHPexpert | last post by:
Regular Expression help needed -------------------------------------------------------------------------------- I want to extract all text that is contained inside the brackets after the word INDIRECT. There must be at least one pair of parentheses, they may be multiple pairs for exampple, this string '=IF($B$9="Off",0,INDIRECT(ADDRESS(1(8),COLUMNS($A$41:C41),,,$B$9 )),()aaaa' has four bracket pairings until the initial "(" is...
2
945
by: ananth | last post by:
Hi All, I have written a code that finds default mail client and then i am using a function to open a mail client and populating it with values.The code works fine when i give some minimum value for the BODY field of the mail.But when i pass String Values with large amount of data the code is not working out.What is this problem due to?I have attached the code below Option Explicit Private Declare Function ShellExecute Lib...
0
2590
by: Christopher | last post by:
Urgent Help Needed: The EPVH-1.1 Visual Hull Library. Dear All, I am a student doing research in computer vision. The EPVH-1.1 Visual Hull Library will really help a lot in my research. I did have this library before but I didn't keep my copy of this library because I always thought I could download it again form internet. However, the author of this library closed the download
1
2616
by: Joel Fireman | last post by:
Help Needed: Upgrade Fedora 4 / Apache 2 to PHP 5.2.x from 5.0.4 I've been testing Joomla as a content manager for the County offices, and it looks pretty good. Unfortunately, I decided to upgrade it from the 1.0.13 version to 1.5 as we get ready to go live with the web site... and the update installation gives an error in XML processing, which seems (from what I've been able to dredge up in forum discussions) to stem from a known bug in...
0
8674
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9262
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
9125
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...
0
8970
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...
0
7876
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5923
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
4434
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
3127
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
2463
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.