Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

asp.net - What happens if an exception occurs in Catch block in C#. Also what would be the caller result in that case

It was an interview question, quite simple, but I am not confident about the answer.

What happens if an exception occurs in catch block ?

I am trying to give an example small prog of what the interviewer was trying to ask me, please correct my program if it is not compiling, I am really new to this. Bottom line is what happens if an exception occurs in Catch and what will be the value of caller int hat case.

For instance, I have the following:

double Calculate(int x)
{
    try
    {
        x = x/2;
    }
    catch(Exception ex)
    {
        Console.Writeline("Message: "+ ex.Message);
    }
    finally
    {
      x = 10;
    }
    return x;
}

double myResult = Calculate(x); //x can be any number or 0 for example

Now there are two questions:

  1. What happens if an exception happens in catch block ? Also, how to resolve it ? (This is simple example of what the interviewer was asking a similar question).

  2. What will happen to myResult if an exception happens in Calculate(x) method ?What will be its value in all cases ? (Please explain every case with an example)

I would like to understand this with a detailed explanation too.

Thank you so much.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An exception thrown in a catch block will behave the same as an exception thrown without it - it will go up the stack until it is caught in a higher level catch block, if one exists. Doing this is quite normal if you want to change or wrap the original exception; i.e.:

public void MyStartMethod
{
    try
    {
        //do something
        MyBadMethod();
    }
    catch(MySpecialException mse)
    {
        //this is the higher level catch block, specifically catching MySpecialException 
    }
}

public void MyBadMethod()
{
    try
    {
        //do something silly that causes an exception
    }
    catch (Exception e)
    {
        //do some logging

        throw new MySpecialException(e);
    }
}

public class MySpecialException : Exception 
{   
    public MySpecialException(Exception e) { ...etc... }
}

In your case, myResult will have whatever value it had before, if it's even still in scope.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...