How can I make ex accessible after a try catch block?
Like this...
try
{
// do something...
}
catch (Exception ex) {
// skip here...
}
//execute **ex** here
Why do I want to do this?
If I write:
try
{
// do something...
// i already declared x as public.
x = "what ever";
}
catch (Exception ex) {
// if there's an error...
Console.WriteLine(ex);
}
// Even there's an error,
// there's still no output.
So maybe if ex is public, I can try this:
try
{
// do something...
}
catch (Exception ex) {
// skip here...
}
// execute **ex** here
I am not sure what you mean with "execute ex", but this is how you could access the Exception after the catch block:
Exception ex = null;
try
{
// do something...
}
catch (Exception ex1) {
ex = ex1;
}
if(ex != null)
// ...
Exception exceptionObject = null;
try
{
// do something...
}
catch (Exception ex) {
exceptionObject = ex;
}
// execute **ex** here
if(exceptionObject != null)
{
//do a thing
}
The thing you are doing is weird. Stop it.
Related
Code:
try
{
RegistryKey SQMRegKey = Registry.LocalMachine.OpenSubKey("CurrentControlSet\\Control\\WMI\\Autologger", true);
//SQMRegKey.DeleteSubKey("SQMLogger");
SQMRegKey.DeleteSubKeyTree("SQMLogger");
SQMRegKey.Close();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString());
}
always throws exception System.NullReferenceException:Object reference not set to an instance of an object
The registry path is not correct. Please use the below modified code:
try
{
RegistryKey SQMRegKey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Control\\WMI\\Autologger", true);
//SQMRegKey.DeleteSubKey("SQMLogger");
SQMRegKey.DeleteSubKeyTree("SQMLogger");
SQMRegKey.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
OpenSubKey may fail, in which case the return value is null. You use the reference, i.e. SQMRegKey without checking if it actually points to a valid object.
try
{
var SQMRegKey = Registry.LocalMachine.OpenSubKey("CurrentControlSet\\Control\\WMI\\Autologger", true);
if(SQMRegKey != null)
{
SQMRegKey.DeleteSubKeyTree("SQMLogger");
SQMRegKey.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString());
}
I don't understand why but I'm receiving Flurl Exceptions and those are not being caught by the try/catch block. Any ideas on why that's happening?
Here's the code:
try
{
var x = await Utils.Sales.GetUrl()
.PostJsonAsync(new Sale
{
MerchantId = Constants.Sandbox.MerchantId
})
.ReceiveJson<Sale>();
var b = x;
}
catch (FlurlHttpTimeoutException)
{
//LogError("Timed out!"); //todo:
}
catch (FlurlHttpException ex)
{
var x = ex.Message;
//todo:
//if (ex.Call.Response != null)
// LogError("Failed with response code " + call.Response.StatusCode);
//else
// LogError("Totally failed before getting a response! " + ex.Message);
}
catch (Exception ex)
{
var a = ex.Message;
}
Here's the output (the only reason why I know the exception is being thrown):
Maybe this page will help https://msdn.microsoft.com/zh-cn/library/jj619227.aspx
Sorry don't have a english version, you can try google translate it.
It's someting wrong with you catch exception type or await code.
Try this way catch your exception:
```
try
{
await t1;
}
catch (AggregateException ex)
{
var innerEx = ex.InnerExceptions[0];
if (innerEx is NotSupportedException)
{
...
}
else if (innerEx is NotImplementedException)
{
...
}
else
{
...
}
}
```
Is there a way when catching an exception to determine if it were constructed with a non-default message.
try
{
throw new Exception(message); // case 1
//throw new Exception(); // case 2
}
catch(Exception exp)
{
/* what do I put here such that if the case 2 exception were
caught it would output exp.ToString() instead of exp.Message? */
textBox1.Text = exp.Message; // case 1 handeling
}
Just to clarify when Exception(message) is thrown I want it to ouptut exp.Message and when Exception() is thrown I want to output exp.ToString(). I would prefer to accomplish this without adding a custom exception. Thanks.
You need to check the message against a default exception
catch (Exception e)
{
bool isDefaultMessage = e.Message == new Exception().Message;
}
Update
Difference types of Exception
catch (Exception e)
{
bool isDefaultMessage = false;
try
{
var x = (Exception) Activator.CreateInstance(e.GetType());
isDefaultMessage = e.Message == x.Message;
}
catch (Exception) {} // cannot create default exception.
}
I have this code
protected void Button_Click(object sender, EventArgs e)
{
try
{
// some code
con.Open();
string result = command.ExecuteScalar().ToString();
if (result != string.Empty)
{
// some code
Response.Redirect("Default.aspx");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
con.Close();
}
It gives an exception from Response.Redirect("Default.aspx");
ex: Thread was being aborted.
any idea why?
thanx
Redirecting from within a Try...Catch statement will result in this Exception being thrown, so this is not what you want to do.
I would update your code to;
string result = string.Empty;
try
{
// some code
con.Open();
result = command.ExecuteScalar().ToString();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
con.Close();
}
if (result != string.Empty)
{
// some code
Response.Redirect("Default.aspx");
}
This is a typical Exception that is thrown by ASP.NET when performing a redirect. It's quite well documented on the Interweb.
Try the following catch block to swallow the exception and all should be fine. It's supposed to do nothing!
catch(ThreadAbortException)
{
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
con.Close();
}
Is either one of these risky? Is one better? Or is it one of those things you print out and throw a dart at to decide?
I want to do this now that I understand how finally works:
try {
stuff that changes something...
}
catch (System.Exception ex) {
something.worked = false;
something.err = ex.Message;
}
finally {
stuff.close();
return something;
}
But I've seen:
try {
stuff that changes something...
return something;
}
catch (System.Exception ex) {
something.worked = false;
something.err = ex.Message;
return something;
}
finally {
stuff.close();
}
You can't return from finally. You will get compiler error:
Control cannot leave the body of a finally clause
If target class implements IDisposable then I would do next:
using (stuff s = new stuff())
{
return stuff;
}
or
using (stuff s = new stuff())
{
try
{
// do stuff
return stuff;
}
catch (Exception ex)
{
// do logging or another stuff
return something;
}
}
will call Dispose() for you if that will be required/possible.
Personally I would do neither and would use
try {
stuff that changes something...
}
catch (System.Exception ex) {
something.worked = false;
something.err = ex.Message;
}
finally {
stuff.close();
}
return something;
Also in the finally statement, check that you need to close/dispose of objects as they might have never been opened/set if they have failed.
Also see here Is it bad practice to return from within a try catch finally block?
There is no risk in the second approach. But it allows you to return different values in case of exceptions.