如果在C#中的Catch块中发生exception会发生什么。 在这种情况下,调用者结果也是如此

这是一个面试问题,很简单,但我对答案没有信心。

如果catch块中发生exception会发生什么?

我试图举例说明面试官试图问我的小编,请纠正我的程序如果没有编译,我真的很新。 如果在Catch中发生exception并且调用者int hat的值是什么,那么底线是会发生什么。

例如,我有以下内容:

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 

现在有两个问题:

  1. 如果catch块中发生exception会发生什么? 另外,如何解决? (这是面试官提出类似问题的简单例子)。

  2. 如果在Calculate(x)方法中发生exception,myResult会发生什么?在所有情况下它的价值是什么? (请用例子解释每个案例)

我想通过详细解释来理解这一点。

非常感谢。

catch块中抛出的exception将与没有它时抛出的exception相同 – 它将向上移动,直到它被捕获到更高级别的catch块(如果存在)。 如果您想要更改或包装原始exception,这样做是很正常的; 即:

 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... } } 

在你的情况下, myResult将具有之前的任何价值,如果它仍然在范围内。

以下信息将有所帮助(从我以前的答案到相关问题)。 如果你的catch块抛出exception并且没有其它catch块来处理它除了引起它的那个之外,它将继续被重新抛出然后’Windows处理它’。

如果发生exception,CLR会遍历调用堆栈以查找匹配的catch表达式。 如果CLR没有找到匹配的,或者每次都重新抛出exception,则Exception会从Main()方法中冒出来。 在这种情况下,Windows处理exception。

控制台应用程序的事件处理是最容易理解的,因为CLR没有特殊处理。 如果没有捕获,则exception将离开应用程序线程。 CLR打开一个窗口,要求调试或退出应用程序。 如果用户选择调试,则启动调试器。 如果用户选择关闭,则应用程序退出并且exception被序列化并写入控制台。

catch中的exception基本上表现就好像没有catch块一样开始。 您可以在多层代码中看到此模式,您可以在其中重新抛出exception。 这是您的示例的略微变化,但结果非常相似。

 try {} catch { throw; } 

在上面的情况下,在您的情况下,exception被认为是未处理的,因为它仍在向上传播。

没有回报价值。 如果没有其他catch块来处理它,程序就会失败。

如果它是子函数,则exception将被发送到调用函数的catch块

如果它是一个main函数,则会抛出exception,并由调用方法处理或不处理

其次,我们不会在catch块中写任何可能导致exception的内容。

它们通常用于抛出或记录exception。

即使有什么东西你可以使用Finally块,以便可以重新获得任何占用的资源。

catch的常见用法最后是在try块中获取和使用资源,处理catch块中的exception情况,并释放finally块中的资源。

MSDN文档

没有真正的回报价值。 例外将“返回”。

这是编译器可接受的代码:

 public bool fooMethod() { throw new NotImplementedException(); } 

在您的情况下, myResult不会被更改。

我同意TheEvilPenguin。 只需在catch部分再试一次try / catch。 我没有运行代码,但是无论是否存在exception,finally部分总是会运行,因此x等于10。

这是我今天写的疯狂代码。 如您所见,我在代码的catch部分放了一个try / catch:

  if (days >= 180 || inStock == false) { if (mainGetSet.OrderID != MainGetSet.EMAILCANCELO) { if (debugging == true) { MessageBox.Show("Here is where support will get an email instead of it being canceled. Order ID: " + mainGetSet.OrderID); } string subject = "Please check order " + mainGetSet.OrderID + " to ascertain if possible cancel action is needed."; string body = "Dear Support \r\n \r\nPlease check order " + mainGetSet.OrderID + " to confirm if a possible cancel action is needed " + "and please process manually. Here is the SKU " + childGetSet.Sku + ". Thank you. " + " \r\n \r\n Kind Regards, \r\n IT Department"; sendEmail.SendEmailToSupport(subject, body); // Database call to the cancel order DB CanceledDB.AddJSONInfo(childGetSet); //readyResponse = CancelKiboOrder.MakeOrderCanceled(token, mainGetSet.OrderID); } MainGetSet.EMAILCANCELO = mainGetSet.OrderID; } else { if (debugging == true) { MessageBox.Show("Here is where support will get an email about the backorder date. Order ID: " + mainGetSet.OrderID); } //DateTime backorder180 = new DateTime().AddDays(days); //string backOrder = backorder180.ToString("yyyy-MM-dd'T'HH:mm:ss"); string backOrder = DateTime.UtcNow.AddDays(days).ToString("s") + "Z"; string ItemsQty = string.Empty; for (int iq = 0; iq < jsonGetSet.OrderItemID.Count; iq++) { //ItemsQty += "{ \r\n \"autoAssign\":false,\r\n \"locationID\":169309,\r\n \"shipmentStatus\":\"READY\",\r\n \"itemAssign\":[ \r\n { \r\n \"orderItemID\":" + jsonGetSet.OrderItemID[iq] + ",\r\n \"quantity\":" + jsonGetSet.Quantity[iq] + "\r\n }\r\n ]\r\n }\r\n"; ItemsQty += " {\r\n \"shipmentStatus\":\"BACKORDER\",\r\n \"backOrderReleaseDate\":\"" + backOrder + "\",\r\n \"itemAssign\":[\r\n {\r\n \"orderItemID\":" + jsonGetSet.OrderItemID[iq] + ",\r\n \"quantity\":" + jsonGetSet.Quantity[iq] + "\r\n }\r\n ]\r\n }\r\n "; if (jsonGetSet.OrderItemID.Count > 0 && iq < jsonGetSet.OrderItemID.Count - 1) { ItemsQty += ","; } } if (debugging == true) { MessageBox.Show(ItemsQty); } string subject = "Please check backorder number " + mainGetSet.OrderID + " to ascertain the reason."; string body = "Dear Support \r\n \r\nPlease check backorder number " + mainGetSet.OrderID + " to confirm the backorder. " + "Here is the SKU " + childGetSet.Sku + "."+ " \r\n \r\n Kind Regards, \r\n IT Department"; sendEmail.SendEmailToSupport(subject, body); readyResponse = Backorder.MakeOrderBackorder(token, mainGetSet.OrderID, ItemsQty); } if (debugging == true) { DebugOutput(readyResponse, textBox); } var parsedReady = new JObject(); try { parsedReady = JObject.Parse(readyResponse); } catch (Exception JEx) { if (debugging == true) { MessageBox.Show("The program threw an Exception: " + JEx); } else { string messageSubject = "There was a problem with the JSON for the BackOrder in KIBO."; string messageBody = "There was a problem with the JSON for the BackOrder in KIBO. Error: " + "\r\n \r\n \r\n Here is the JSON returned: " + parsedReady; string kiboSendEmail = string.Empty; kiboSendEmail = sendEmail.SendEmailCS(messageSubject, messageBody, JEx); if (mainGetSet.OrderID != MainGetSet.EMAILCANCELO) { if (debugging == true) { MessageBox.Show("Here is where support will get an email instead of it being canceled. Order ID: " + mainGetSet.OrderID); } string subject = "Please check order " + mainGetSet.OrderID + " to ascertain if possible cancel action is needed."; string body = "Dear Support \r\n \r\nPlease check order " + mainGetSet.OrderID + " to confirm if a possible cancel action is needed " + "and please process manually. Here is the SKU " + childGetSet.Sku + ". Thank you. " + " \r\n \r\n Kind Regards, \r\n IT Department"; sendEmail.SendEmailToSupport(subject, body); // Database call to the cancel order DB CanceledDB.AddJSONInfo(childGetSet); //readyResponse = CancelKiboOrder.MakeOrderCanceled(token, mainGetSet.OrderID); } MainGetSet.EMAILCANCELO = mainGetSet.OrderID; { if (debugging == true) { MessageBox.Show("Here is where support will get an email about the backorder date. Order ID: " + mainGetSet.OrderID); } //DateTime backorder180 = new DateTime().AddDays(days); //string backOrder = backorder180.ToString("yyyy-MM-dd'T'HH:mm:ss"); string backOrder = DateTime.UtcNow.AddDays(days).ToString("s") + "Z"; string ItemsQty = string.Empty; for (int iq = 0; iq < jsonGetSet.OrderItemID.Count; iq++) { //ItemsQty += "{ \r\n \"autoAssign\":false,\r\n \"locationID\":169309,\r\n \"shipmentStatus\":\"READY\",\r\n \"itemAssign\":[ \r\n { \r\n \"orderItemID\":" + jsonGetSet.OrderItemID[iq] + ",\r\n \"quantity\":" + jsonGetSet.Quantity[iq] + "\r\n }\r\n ]\r\n }\r\n"; ItemsQty += " {\r\n \"shipmentStatus\":\"BACKORDER\",\r\n \"backOrderReleaseDate\":\"" + backOrder + "\",\r\n \"itemAssign\":[\r\n {\r\n \"orderItemID\":" + jsonGetSet.OrderItemID[iq] + ",\r\n \"quantity\":" + jsonGetSet.Quantity[iq] + "\r\n }\r\n ]\r\n }\r\n "; if (jsonGetSet.OrderItemID.Count > 0 && iq < jsonGetSet.OrderItemID.Count - 1) { ItemsQty += ","; } } if (debugging == true) { MessageBox.Show(ItemsQty); } string subject = "Please check backorder number " + mainGetSet.OrderID + " to ascertain the reason."; string body = "Dear Support \r\n \r\nPlease check backorder number " + mainGetSet.OrderID + " to confirm the backorder. " + "Here is the SKU " + childGetSet.Sku + "." + " \r\n \r\n Kind Regards, \r\n IT Department"; sendEmail.SendEmailToSupport(subject, body); readyResponse = Backorder.MakeOrderBackorder(token, mainGetSet.OrderID, ItemsQty); } if (debugging == true) { DebugOutput(readyResponse, textBox); } parsedReady = new JObject(); try { parsedReady = JObject.Parse(readyResponse); } catch (Exception Jx) { if (debugging == true) { MessageBox.Show("The program threw an Exception: " + Jx); } else { messageSubject = "There was a problem with the JSON for the BackOrder in KIBO."; messageBody = "There was a problem with the JSON for the BackOrder in KIBO. Error: " + "\r\n \r\n \r\n Here is the JSON returned: " + parsedReady; kiboSendEmail = string.Empty; kiboSendEmail = sendEmail.SendEmailCS(messageSubject, messageBody, JEx); } }