Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Throwing Exception 1

Status
Not open for further replies.

IlyaRabyy

Programmer
Nov 9, 2010
568
US
Colleagues,

Going through the existing (and working) program came across the following code (it's in C#, though, but in the same .NET, so what's a slight difference in syntax? ;-) ):

Code:
if (!Directory.Exists(outputFolder)) throw new Exception(String.Format("Output folder '{0}' not found.", outputFolder))

Throwing Exception is not the same as handling exception, say, with Try-Catch-End Try construct ("But of course!" - Q in James Bond films :) ).
And in this code, handling error this is not: the next line is not Return or anything like that, just another valid command:

Code:
string[] inputFiles = ctx.getFiles(RepositoryTrunk.Run, "*.pdf")

So, what may be the purpose of throwing Exception without any following action?

Regards,

Ilya
 
The purpose of throwing an Exception like this is to halt processing of the code and return the Exception to whatever procedure called this code. When the exception is thrown, it stops processing at that point and returns the Exception object to the calling code. If that code has a Try...Catch block around it, the Exception will be handled there. If the calling code is not in a Try...Catch block, then the code will stop processing again, and the Exception will be thrown again, until the error is either handled or the calling stack is exhausted and the program throws it as an unhandled Exception.

In short, Throwing an Exception does act as a Return statement of a sort, and the calling code handles the Exception.

I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top