Can anybody please help me with these questions. I have an upcoming exam, and I'm sure this question will appear. Thank You.

(a) What is exception handling?

(b) Write a C# code segment that demonstrates how to catch an
exception when a String variable cannot be converted to an Integer
type variable?

(c) Demonstrate using a suitable C# code segment how a divide-byzero error may be caught.

Recommended Answers

All 4 Replies

Exception Handling
Exception handling is used to catch errors/bugs in code. When there is an error/bug, it will "throw" a message or Exception that has information on what the error was. Exception handling code "catches" the message that was thrown, basically saving the program from crashing.
String to Int Exception

try
{
    Int32.TryParse(StringToConvert, out IntOfString); 
    // This tries to convert a String to an Int. 
    //If it can convert it, IntOfString will be the Int version of the string.
    //If it cannot convert it, it will throw an exception saying what the error was.
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message); 
    // This will display what the error is.
}

Divide By Zero Exception

try
{
    int OutputNumber = 1000 / 0; 
    // Try to divide by zero.
}
catch (DivideByZeroException ex)
{
    Console.WriteLine(ex.Message);
    //Displays what the error is.
}

Tip: When catching exceptions, it is a good idea to use Exception instead of a specific exception like DivideByZeroException so you can catch all the errors.

Hope this helps!

Tip: When catching exceptions, it is a good idea to use Exception instead of a specific exception like DivideByZeroException so you can catch all the errors

This is really bad advice. Never catch Exception, always catch the specific exception. How can you recover from an exception if you don't know what type it is? How will you figure out what errors you are having if you just have the generic exception.

No guide on programming will ever tell you to catch a general exception.

You could use it to catch all errors, then use Exception.Message to find what the error was, then implement the exception that it was.

Momerath is right. The message isn't a very good way to determine the exception origin.

You can use multiple catch blocks for each expected exception type, and 1 final one with the general exception:

try
{
    int i = x / y;
}
catch (DivideByZeroException ex)
{
     Console.Writeline("Divide by zero caught" + Environment.Newline + ex.Message);
}
catch (Exception ex)
{
     Console.Writeline("Unexpected exception caught" + Environment.Newline + ex.Message);
}
finally
{
      Console.Writeline("Done");
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.