try/catch, return from catch ?

Is this baaad?

try
{
    m_Database.OpenEx( sDSN );
    return TRUE;
}
catch( CDBException* pxE )
{
    pxE->Delete();
    return FALSE;
}

or MUST I exist the try/catch clause first before returning to allow some
kind of clean up?

e.g.

BOOL bFail = FALSE;
try
{
    m_Database.OpenEx( sDSN );
}
catch( CDBException* pxE )
{
    pxE->Delete();
    bFail = TRUE;
}
return !bFail;


Lisa


0
no6060 (315)
1/15/2004 8:33:35 AM
vc.mfc 33608 articles. 0 followers. Follow

4 Replies
1036 Views

Similar Articles

[PageSpeed] 24

The second method is better method. It will allow cleanup tooo if 
required. But i think it is not a good idea to write code which includes 
negations as it can be written without that. In the second code it is 
written as "return !bFail. it can be written as "return bFail" which 
will make the code more natural and clear. There is no need to write in 
the otherway which includes a negated statement.

like this:

BOOL bFail = TRUE
 > try
 > {
 >     m_Database.OpenEx( sDSN );
 > }
 > catch( CDBException* pxE )
 > {
 >     pxE->Delete();
 >     bFail = FALSE;
 > }
 > return(bFail);

Sreeram

Lisa Pearlson wrote:

> Is this baaad?
> 
> try
> {
>     m_Database.OpenEx( sDSN );
>     return TRUE;
> }
> catch( CDBException* pxE )
> {
>     pxE->Delete();
>     return FALSE;
> }
> 
> or MUST I exist the try/catch clause first before returning to allow some
> kind of clean up?
> 
> e.g.
> 
> BOOL bFail = FALSE;
> try
> {
>     m_Database.OpenEx( sDSN );
> }
> catch( CDBException* pxE )
> {
>     pxE->Delete();
>     bFail = TRUE;
> }
> return !bFail;
> 
> 
> Lisa
> 
> 

0
1/15/2004 9:12:56 AM
"Lisa Pearlson" <no@spam.plz> wrote (abridged):
> or MUST I exist the try/catch clause first before returning to allow some
> kind of clean up?

You can return from a catch block. Catch blocks are not special in this
regard.

Some people dislike multiple returns for style reasons, but that is a
general issue and controversial. Personally I usually prefer multiple
returns to spurious mutable state. Your version with bFail is harder to read
because we have to track all possible assignments to that variable.

-- Dave Harris


0
dharris1 (20)
1/15/2004 3:06:22 PM
But i feel that most of the people would prefer a single return than as many
return. which improves code
redability and easy error handling too..

i preferred single return as much as possible..
Jibesh.

"Dave Harris" <dharris@serif.com> wrote in message
news:ObJEMl32DHA.536@tk2msftngp13.phx.gbl...
> "Lisa Pearlson" <no@spam.plz> wrote (abridged):
> > or MUST I exist the try/catch clause first before returning to allow
some
> > kind of clean up?
>
> You can return from a catch block. Catch blocks are not special in this
> regard.
>
> Some people dislike multiple returns for style reasons, but that is a
> general issue and controversial. Personally I usually prefer multiple
> returns to spurious mutable state. Your version with bFail is harder to
read
> because we have to track all possible assignments to that variable.
>
> -- Dave Harris
>
>


0
jibesh.vp (92)
1/24/2004 7:28:02 PM
jibesh wrote:

>But i feel that most of the people would prefer a single return than as many
>return. which improves code
>redability and easy error handling too..

Readability is not enhanced by having to introduce artificial variables and
check on them throughout a function to determine the state the function is
in, which is often necessary when forcing single return upon a function.

Error handling may be improved by single return in a language like C, where
it's common to concentrate error handling at the end of a function, label it
"out", and use "goto out" to get there upon errors. However, most of the
error handling that goes on in these goto targets should be taken care of by
local object destructors in C++, and the "real" error handling is isolated
in the relatively few try/catch blocks, which are found at relatively
"outer" levels of the program. Good C++ practice is to use local object
dtors in the RAII technique to deal with exceptions anyway, and this also
takes care of clean up issues for early return; you can safely use early
return in C++ instead of the C-style "goto out".

>i preferred single return as much as possible..

People argue endlessly over early returns vs. single return.IMO, it's
misguided to insist on single return when early return allows you to express
an idea more naturally and directly. Here's a pointer into a thread in which
it's been discussed to death:

http://groups.google.com/groups?as_umsgid=fc3dfv8jeegdbph7q6neagt8v7bppo71be@4ax.com

Google says it's at 373 messages, so it should keep you busy for a while!
But be sure to check out the two papers I linked to in that message:

http://www.cis.temple.edu/~ingargio/cis71/software/roberts/documents/loopexit.txt
http://www.cs.virginia.edu/~evans/cs655/readings/bwk-on-pascal.html

-- 
Doug Harrison
Microsoft MVP - Visual C++
0
dsh (2498)
1/24/2004 10:33:11 PM
Reply:

Similar Artilces:

trying this out
This is a test posting. On Tue, 13 Nov 2007 16:06:51 +0800, "hmmmm" <bobo123@dotdot.dyndns.org> wrote: >This is a test posting. > Please use microsoft.public.test or microsoft.public.test.here for your testing. This is a working newsgroup. If you have questions about an Access database, please post them. John W. Vinson [MVP] ...

I am trying to round up to the nearest 25 cents
I am trying to round a money value to the nearsest 25 cents and it keeps rounding to the nearest dollar HELP Try =CEILING(A1, 0.25) In article <2DB8F007-1E27-4A48-923B-C7D4D0238B5E@microsoft.com>, sypher <sypher@discussions.microsoft.com> wrote: > I am trying to round a money value to the nearsest 25 cents and it keeps > rounding to the nearest dollar HELP =ROUND(A1*4,0)/4 -- HTH Bob Phillips "sypher" <sypher@discussions.microsoft.com> wrote in message news:2DB8F007-1E27-4A48-923B-C7D4D0238B5E@microsoft.com... > I am trying to round a mone...

Trying to clear up Received but not invoiced report
I am trying to clean up the received not invoiced items. The problem began with entering a purchase order and then not matching the invoice to the items received agaisnt the purchase order. SO we thought that doing a returned transaction entery would solve the problem. The only thing is now the return shows up on our Received/ Not invoiced report. And the report is becoming a huge mess and difficult to use. What is the best way to clear up items that have been received but were not matched and already paid through the invoice entery? There is a knowledgebase article on this very thing av...

MSQuery not returning new data...
I am using MSQuery to query our database and return values to Excel. I will be returning this information monthly, so every month I want to see the current month's data. Some of my queries are able to be represented graphically in MSQuery, so I set up a prompt for criteria to enter the month and year of the information I want for my query. Works great... Several of the queries are too complex to be represented graphically so (I believe) I cannot set a criteria the way I did on the others. I believe it is mainly the use of subselects that is causing this. No big deal. I just set a v...

send/receive (2nd try)
New computer. Microsoft XP Home. Microsoft Office XP Small Business 2002. Earthlink dial-up account. Two e- mail accounts. After opening Outlook, 1st send/receive (option 3, all accounts) usually prompts for both passwords, downloads messages, all good. Next time, though, no prompt for account 2, error cannot connect to server, account 1 usually gets messages. Every five minute send/receive option eventually degenerates to cannot connect to server errors for both accounts. Meanwhile internet browsing slows to a crawl. Any ideas? ...

How do I cancel a msg Outlook keeps trying to send unsuccessfully?
How do I cancel an "in process" email Outlook keeps trying to send unsuccessfully due to a huge email message I tried to send with way too many attachments? It's stuck in "send" mode, and as a result, I can't send any emails because Outlook cannot get past trying to send this message. How do I cancel a pending outbox transmission while it's trying to send? I've tried everything I can think of to no avail. Please help! Angelczech wrote on Fri, 12 March 2010 07:32 > How do I cancel an "in process" email Outlook keeps trying to send ...

trying to insert a 0 in front of zipcode
Hello, I do not use excel at all so i have no clue! I have a list of daycares that i want to create mailing labels with...about 700 of them but the problem is my zipcode column there needs to be a zero in front of all 700 zipcodes how to i insert a zero in front of them without having to type it into each box? the other question is can i print labels directly from excel or do i have to go thru ms word? thanks Greg One of these 1) format the cells with custom format 00000 2) format the cells with Special / Zip Codes 3) format the cells as Text 4) begin all zip codes with an sin...

error message when trying to install WMP 10 or 11
My operating system is Windows XP Home Edition 2002. I'm trying to download either WMP 10 or 11 and I get a message saying it was not possible to complete setup, see webhelp for more assistance, however there is no additional information when I click Web help. the Error message is 8007F0DA. Can anyone help me? Thanks. On Tue, 30 Mar 2010 07:54:01 -0700, Nate <Nate@discussions.microsoft.com> wrote: > >My operating system is Windows XP Home Edition 2002. I'm trying to download >either WMP 10 or 11 and I get a message saying it was not possible to &g...

Try or TRY
Hello, Will there be any opitmization or ... when we use INT or TRY macros instead of int or try ? Which one is better to be used? Thanks, JSmith "JSmith" <jsmithmitra@yahoo.com> wrote in message news:%23G1sOVdoEHA.692@TK2MSFTNGP12.phx.gbl... > > Hello, > > Will there be any opitmization or ... when we use INT or TRY macros instead > of int or try ? Which one is better to be used? http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore/html/_core_exceptions.3a_.converting_from_mfc_exception_macros.asp -- Jeff Partch [VC++ MVP] FYI, TRY ...

error message when trying to delete messages in inbox
I cannot delete messages in my email inbox. When attempting to delete messages, Outlook says "The messaging interface has returned an unknown error. If the problem persists, restart Outlook. I continue to get the message even though I restarted Outlook. My mail works fine, but I just cannot delete anything. Does someone know a solution? Can you delete them if you hold shift as you delete? How many items are in the deleted items folder? Are you using any type of AV scanner on the message store? -- Diane Poremsky [MVP - Outlook] Author, Teach Yourself Outlook 2003 in 24 Hours Coa...

New to Userforms
I have never programmed for a userform before, so I may need precise help here. On a worksheet tab called 'Tables', I have a list of ZIP Codes with City and County. The single column of ZIP Codes is a named range (ZIPS). Some of the ZIP Codes are in the table two times, for instance, 90028.1 / Hollywood N of Sunset / Los Angeles (County) 90028.2 / Hollywood S of Sunset / Los Angeles 90038.1 / Hollywood N of Santa Monica / Los Angeles 90038.2 / Hollywood S of Santa Monica / Los Angeles What I am looking for is when a user enters the ZIP Code of 90028, I would like th...

Problem trying to export e-mail messages
When I go into Windows Mail and export my messages, the export completes but then I go and the folders don't match my existing e-mail folders. There are folders showing which I had deleted months ago. Could it be a corrupt file? How can I just transfer the e-mail messages I need to a new PC with Windows 7? Thanks> Windows Mail uses internal mail folder names that may not correspond exactly to the folder name in the user interface. What are you doing with your Windows Mail messages in Windows 7? Windows Mail was not designed to run on Windows 7. --=20 Gary VanderMole...

try/catch vs TRY/CATCH
Hi, What is in your opinion the preferred way of doing exception handling for MFC objects (such as the CFile)... the try/catch mechanism or the MFC based TRY/CATCH macros? Thanks Adeel Use try/catch. I don't recall what TRY/CATCH does but, basically, that was provided before VC++ had full support fro try/catch. -- Jonathan Wood SoftCircuits Programming http://www.softcircuits.com "Adeel" <dontWantSpam@All> wrote in message news:ORLqQz3fGHA.4568@TK2MSFTNGP03.phx.gbl... > Hi, > > What is in your opinion the preferred way of doing exception handling for ...

Trying to finish up a worksheet function (if/or??)
Okay, here are the details and the exact data: A12 thru A17 = Income Source (text, user defined [examples would be Social Security, Pension, etc.]) B12 thru B17 = Amount Received (will be currency in $dddd.cc format) C12 thru C17 = Tax Deductible? (currenty have a drop-down list option, YES or NO) A18 = Subtotal (text) B18 = Subtotal (calculated sum of above columns) C18= [empty] A20 = Choose an Investor (text) B20 = Investor name (from drop down list) C20 = Mark up amount (i.e., 125%, would like it to auto fill from the investor chosen) A22 = Total (text) B22 = Total (calculated su...

Run Time error when trying to use DMax on a line value
Please can someone help me with run time error I am getting when I try to use a DMax function on a LineID control in a subform. I have a main form frmDeliveries and a subform sfrmDeliveryDetails They are linked on master and child by a DeliveryID control. On the sfrmDeliveryDetails BeforeUpdate I entered : Private Sub Form_BeforeInsert(Cancel As Integer) Me![LineID] = Nz(DMax("[LineID]", "[sfrmDeliveryDetails]"), 0) + 1 End Sub (which I modified from a previous posting) When I try to enter a selection from a Productscombo on the sfrmDeliveriesDetails I get a Run Ti...

Processing returns/credits
How should I handle returns? For instance, let's say that during November I purchased $300 in clothing from Lazarus, using my debit card, but returned $50. The store credited my checking account the $50 for the return. I enter the transaction as a credit to the payee (Lazarus). Does MS Money then think I've spent $250 on clothes for the month, or $350? My bottom line is that I want the expense categories to accurately reflect expenses and it's not at all unusual for me to make clothing returns as I'm the primary buyer for my family. Thank you. Many of us just r...

vlookup returns na
Hi all! Sheet1 contains the following: Col_H Col_O 302 33937 158 32840 3582 73345 39760 73455 4412 AGL92 2941 AHW92 136 30044 Sheet2 contains this: Col_H 34132 34332 33532 31032 34433 34633 33937 This is the function I use along Col_I: =IF(ISNA(VLOOKUP(H1;Sheet1!$H$1:$O $7;1;FALSE))=TRUE;VLOOKUP(VALUE(H1);Sheet1!$H$1:$O $7;1;FALSE);VLOOKUP(H1;Sheet!$H$1:$O$7;1;FALSE)) For H7 I would expect the function to return 302, but it only retuns #N/A for all rows in Col_H. I use concatenate to generate the data in Col_O in Sheet1. I also tried to copy the valu...

Try that critical pack from Microsoft Corporation
--zyqwganxt Content-Type: multipart/related; boundary="ozwztwhan"; type="multipart/alternative" --ozwztwhan Content-Type: multipart/alternative; boundary="gmqsphxspxalotm" --gmqsphxspxalotm Content-Type: text/plain Content-Transfer-Encoding: quoted-printable MS User this is the latest version of security update, the "October 2003, Cumulative Patch" update which fixes all known security vulnerabilities affecting MS Internet Explorer, MS Outlook and MS Outlook Express as well as three new vulnerabilities. Install now to help protect your computer. Thi...

Excel
Text pasted into a cell from Word or other software will keep the formats including carriage returns, line numbers, tabs, etc. Can text be typed into a cell with control characters that will force this type of formating? -- mwaller If I understood your question correctly - you might try hitting Alt+Enter in order to go to a new line in the same cell Micky "mwaller" wrote: > Text pasted into a cell from Word or other software will keep the formats > including carriage returns, line numbers, tabs, etc. > Can text be typed into a cell with control charac...

trying to email with publisher
Can someone please help me configure this thing!!! I can send a regular email through Windows mail with no problem. I cannot configure Outlook, even though I am using the same info as I used in windows mail. And, most importantly.... I cannot send a Publisher email in either one!!! What in the worl am I doing wrong? They won't go directly to windows mail, even though I have it as my default mail. They continue to go into Outlook even though I have it NOT as my default. They won't send from Outlook, And when I import them into Windows mail, they won't send. Arrrggghhhh! I am...

I am trying to write a macro using If...Then
I am trying to write a macro that will look at the value in column G. If that value is blank or zero, then select the entire row and delete it. Then I want it to populate columns A with a number "111119" and column H with "TEXT" Here's what I tried, but it's not working. (There are other sorts, etc. that precede this item in the macro, that seem to be working fine.) If Range("g:g") < 1 = true Then ActiveWorkbook.Worksheets("Tab3 Upload").Rows.Select Selection.Delete End If If Range("b:b") >...

Catch the Opportunity Close event from OnSave event
Hi, Is anybody aware of a way to catch the event to 'close opportunity' inside the OnSave event. Obviously OnSave is called one last time when an opportunity is closed but since I can not catch it, I can not stop the execution of the section of the javascript code inside OnSave. If not is there a way to do it using callouts or workflow rules etc? Thanks in advance Isil OnSave is only triggered by the 'save' and 'save and close' buttons. I dont think the items in the actions menu trigger it. Callouts and workflow rules can capture the 'close opportunity...

What have you tried?
Interesting read, about people who ask questions on forums. http://mattgemmell.com/2008/12/08/what-have-you-tried AliR. "AliR (VC++ MVP)" <AliR@online.nospam> wrote in message news:3fy%k.6470$hc1.3340@flpi150.ffdc.sbc.com... > Interesting read, about people who ask questions on forums. > > http://mattgemmell.com/2008/12/08/what-have-you-tried > > > AliR. > > <soapbox alert> Amen, brother. I think it's a syndrome brought on by "no discipline" parents and a severely flawed public secondary educational system (to be clear, I&#...

Trying to Catch and Exception
Hi there Today at lunch I tried to learn how to try and catch an exception. I've been wanting to learn how to read the registry in prep for the Scripting Games :) Anyway I can't seem to catch the exact exception I can only catch the generic system.exception even thought $error tell me I have write name. Could someone else try for me <code> $ErrorActionPreference = "stop" Try { Get-ItemProperty -Path "HKCU:\Control Panel\Desktop\" -Name Wallpaper2 } Catch [System.Management.Automation.PSArgumentException] { "caught a PSArgumentExce...

trying to open .CHM help file
Can anyone help me please? i am trying to open a .CHM help file via a command button on my form. I have tried using SHELL but that doesnt work, presumably because it is not a .EXE. any help greatly appreciated Take a look at what Dave Liske has at http://frogleg.mvps.org/helptechnologies/htmlhelp/hhaccess.html -- Doug Steele, Microsoft Access MVP http://I.Am/DougSteele (no e-mails, please!) <simon@geniecom.fsnet.co.uk> wrote in message news:1186572746.714336.269000@q75g2000hsh.googlegroups.com... > Can anyone help me please? i am trying to open a .CHM help file via a > com...