Im a bit new to C# and the syntax so please forgive my ignorance. I have a dotnet page using a C# code behind file and in the C# code there is a try/catch statement with some nested IF/ELSE statements inside it. I need to perform another validation after the initial TRY but before all the IF/ELSE statements. Can you open another try clause before closing it with a catch? Here is an example, Is that syntax correct and can you nest TRY's?
TRY
{
TRY{
IF {
blah;
}
ELSE {
blah;
}
CATCH {
stuff;
}
CATCH {
blah;
}
}
Posted Dec 12, 2007, 7:12 PM
try
{
try
{
if
{
blah;
}
else
{
blah;
}
}
catch
{
stuff;
}
catch
{
blah;
}
Try-catch blocks can be nested within one another, but for simple code samples its not usually necessary. Also, try blocks must be followed by either catch, catch-finally, or finally blocks to be syntatically correct.
Ex:
try
{
//Try to execute some code.
}
catch(
{
//Catch any exceptions.
}
try
{
//Try to execute some code.
}
catch(
{
//Catch any exceptions thrown.
}
finally
{
//This code will execute no matter if an exception
//is thrown or the code executes successfully.
}
try
{
//Try to execute some code.
}
finally
{
//This block will execute regardless
//of if an exceptions is thrown or not.
}
You cannot build a try-catch-finally block without ending it in either catch or finally. But you can nest them as much as you see fit so long as you follow the syntax :)
Also, another nifty tip. If you want to store information for a particular exception that is thrown, you can set up your catch parameter list like this:
try
{
//Try to excecute some code.
//This code may thrown in InvalidOperationException.
}
catch (InvalidOperationException ex)
{
//For console apps
Console.WriteLine(ex.Message);
//For windows apps
MessageBox.Show(ex.Message, "Notice");
}
You can custom catch exceptions and log them, or rethrow them with a friendly error message, like this:
try
{
//Try to execute some code
//This code may throw a FileNotFoundException
}
catch (FileNotFoundException ex)
{
throw new
FileNotFoundException
("Unable to find
}
Probably a little more than you were looking for, but Im sure itll suit you well later on :)