I'm getting unreachable code warning in catch block and I'm not able to debug. Please suggest me how to rectify that bug:
private void HandleDevelopmentServer()
{
string sErrMsg = "";
try
{
QuasarInterfaces.ISecurity oSecurity = null;
Global.CreateSecurityComponent(ref oSecurity);
System.Data.DataSet oDS;
DataTable dtDBSettings = new DataTable();
string sDBString = System.Configuration.ConfigurationSettings.AppSettings["Environment"];
Global.ReadDBConfig(sDBString, ref dtDBSettings);
oSecurity.FetchAllUsers(out oDS, out sErrMsg, dtDBSettings)
if (sErrMsg.Length > 0)
throw new Exception(sErrMsg);
if ((oDS != null) && (oDS.Tables.Count != 0))
{
DropDownList1.DataSource = oDS;
DropDownList1.DataBind();
}
}
catch (Exception e)
{
throw new Exception("HandleDevelopmentServer function failed;" + e.Message);
Global.writeLog("" + e.ToString());
}
}
This line will never happen:
Global.writeLog("" + e.ToString());
You are throwing an exception just above it, meaning this method will exit at that point to the previous in the call stack
By just switching the two it will be fine.
catch (Exception e)
{
Global.writeLog("" + e.ToString());
throw new Exception("HandleDevelopmentServer function failed;" + e.Message);
}
And you can also remove the "" +.
You have to switch the two lines in the catch block so that the log is written before the exception is thrown.
Related
I have an application that assigns a list of values to a DataGridView.
This is done inside a Try catch block.
Occasionally there is an issue with the with the procedure that produces this list (also in a try catch block) and this causes an error when the assignment is done.
It appears the exception is never caught by the block doing the assignment and the application freezes.
Is the exception handled inside the assignment call so that it is not propagated out to the catch block?
The exception produced as a pop up states
"The following exception occurred in the DataGridView:
System.IndexOutOfrangeException: Index 1 does not have a value at
System.Windows.Forms.dataGridViewDataConnection.GetError(Int32 rowIndex)
To replace this default dialog please handle the DataError event"
The code is basically
public void SetupRunners(EventDetails _eventDetails)
{
try
{
RunnerAssociates.Clear();
RunnerAssociates = null;
RunnerAssociates = createRunnerAssociateList(selectedEventDetails);
runnerAssociatesDataGridView.DataSource = RunnerAssociates;
runnerAssociatesDataGridView.DataMember = string.Empty;
}
catch (Exception ex)
{
NZRB_Global.Utils.LogException(methodName, ex);
}
}
private List<Runner_Associate> createRunnerAssociateList(EventDetails _meetAndRace) //NZRB_Global.MeetAndRace _meetAndRace)
{
const string methodName = "createRunnerAssociateList";
List<Runner_Associate> lra = new List<Runner_Associate>();
try
{
if (null != _meetAndRace)
{
_meetAndRace.UpdateAllProfiles();
foreach (RunnerDetail rd in _meetAndRace.runners.runnerList)
{
Runner_Associate ra = new Runner_Associate();
ra.Number = rd.number;
ra.RunnerName = rd.name;
RunnerProfile profile = rd.GetRunnerProfile();
if ((rbJockeyDriver.Checked) || (rbCustom.Checked))
{
ra.AssociateName = rd.person;
}
else if (profile != null)
{
if (rbTrainers.Checked)
{
ra.AssociateName = profile.trainer;
}
else if (rbOwners.Checked)
{
ra.AssociateName = profile.owners;
}
}
lra.Add(ra);
}
}
}
catch (Exception ex)
{
NZRB_Global.Utils.LogException(methodName, ex);
}
return lra;
}
I'm trying to handle an exception I know its ErrorCode is 26, but it does not return the right integer, giving me -2146232060.
Screenshot of QuickWatch with the exception description
So instead of writing this:
catch (SqlException e)
{
if (e.ErrorCode == 26)
{
//my code
}
}
I have to use this:
catch (SqlException e)
{
if (e.Message.ToUpper().Contains("ERROR: 26"))
{
//my code
}
}
Why is it returning -2146232060 and how can I get 26 so I don't need to compare all that string values?
I think what you want to be looking at is SqlException.Number (which is SQL's error number) and not SqlException.ErrorCode (which is the SQL driver error number).
static void Main(string[] args) {
try {
var connection = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb;Initial Catalog=Sandbox;Integrated Security=SSPI;");
connection.Open();
var command = new SqlCommand("throw 50000, 'oops', 1;", connection);
command.ExecuteNonQuery();
}
catch (SqlException ex) {
Console.WriteLine(ex.ErrorCode + ": " + ex.Number + ": " + ex.Message);
for (int i = 0; i < ex.Errors.Count; i++)
Console.WriteLine(ex.Errors[i].Number + ": " + ex.Errors[i].Message);
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
};
}
... yields ...
-2146232060: 50000: oops
50000: oops
Much more information about SqlException on MSDN and about the specific error you are receiving here.
Story: I've 3 functions from 3 different classes. Functions calling order is:
Form1_Load(...) -> Student.GetAllStudents(...) -> StudentDAL.GetStudentInformation(...) -> ConnectionManager.GetConnection(...)
What I want to do is to display StackTrace of the inner most function i.e. ConnectionManager.GetConnection(), in a MessageBox in Form1 class. In other words I don't want to use MessageBox in any inner classes, but only in outer most class that is Form1 class.
Problem: To get inner exceptions we can use InnerException or GetBaseException() etc. but when I try to get inner exception it throws an exception "Object reference not set to an instance", meaning that there is no inner exception and, when I check, the value is also null. All I want to know here why it's null? Shouldn't it be holding reference to the inner exception? Correct me if I'm wrong.
Function codes :
Form1_Load(...)
private void Form1_Load(object sender, EventArgs e)
{
try
{
DataTable dt = new DataTable();
dt.Load((**new Student().GetAllStudents()**));
if (dt.Rows.Count <= 0)
{
MessageBox.Show("Student table empty.");
}
else
{
this.dataGridView1.DataSource = dt;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message+Environment.NewLine+"Source(s) : "+ex.StackTrace.Substring(0, ex.StackTrace.LastIndexOf("at")));
}
GetAllStudents(...)
public SqlDataReader GetAllStudents()
{
try
{
return StudentInformationDataAccessLayer.GetStudentInformation();
}
catch (Exception ex)
{
throw ex;
}
}
GetStudentInformation(...)
public static SqlDataReader GetStudentInformation()
{
try
{
SqlConnection sqlCon = null;
sqlCon = ConnectionManager.GetConnection();
if (sqlCon == null)
{
return null;
}
String Query = null;
Query = "SELECT * FROM [dbo].[Student]";
SqlCommand cmd = new SqlCommand(Query, sqlCon);
SqlDataReader dr = null;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return dr;
}
catch (Exception ex)
{
throw ex;
}
}
GetConnection(...)
public static SqlConnection GetConnection()
{
String _connectionString = null;
_connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
if (_connectionString == null)
{
return null;
}
try
{
SqlConnection connection = new SqlConnection(_connectionString);
connection.Open();
return connection;
}
catch (Exception ex)
{
throw ex;
}
}
If you want stack trace and exception information to be preserved, you should change the code that re-throws caught exceptions like this:
}
catch(Exception ex)
{
// do what you need to do with ex
// ..
// rethrow..
throw; // notice this is not "throw ex";
}
Re-throwing the exception using just throw; preserves the original stack trace. There won't necessarily be an inner exception but that's not what you should care about. What you need to know is the stack trace of where the exception originated.
If you want to re-throw with inner exception set, use below code, but remember that you will lose stack trace:
try
{
...
}
catch (Exception ex)
{
throw new Exception("message", ex);
}
To just re-throw an exception and preserve stack trace, use:
try
{
...
}
catch (Exception ex)
{
throw;
}
Not every exception do actually have an inner exception. First check if inner ex is a null and if it is not then process it.
Having said this, you can of course re-throw your exception like below:
catch(Exception ex)
{
// so smth
// ..
// rethrow..
throw;
}
But please remember two things:
Do not type throw ex, just throw.
Do it only if you really want to do something with this exception before rethrowing. If you don't have such a plan, just don't catch it on this level.
I would do something like:
try
{
...
}
catch (Exception ex)
{
if (ex.InnerException == null)
throw ex;
else
throw ex.InnerException;
}
then at some point where you want to do the stack trace, do something along the lines of:
StackTrace trace = new StackTrace(System.Threading.Thread.CurrentThread, true);
StackFrame[] frames = trace.GetFrames();
string result = string.Empty;
foreach (StackFrame sf in frames)
{
string += sf.GetMethod().Name;
}
MessageBox(result);
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 it possible to return a bool and also rethrow an exception within the same method? Ive tried with the following code and it keeps saying that unreachable code is detected or that i cant exit the finally block.
public bool AccessToFile(string filePath)
{
FileStream source = null;
try
{
source = File.OpenRead(filePath);
source.Close();
return true;
}
catch (UnauthorizedAccessException e)
{
string unAuthorizedStatus = "User does not have sufficient access privileges to open the file: \n\r" + filePath;
unAuthorizedStatus += e.Message;
MessageBox.Show(unAuthorizedStatus, "Error Message:");
throw;
}
catch (Exception e)
{
string generalStatus = null;
if (filePath == null)
{
generalStatus = "General error: \n\r";
}
else
{
generalStatus = filePath + " failed. \n\r";
generalStatus += e.Message;
}
MessageBox.Show(generalStatus, "Error Message:");
throw;
}
finally
{
if (source != null)
{
source.Dispose();
}
}
}
Once you throw an exception, processing in your current method finishes and the exception works up the call stack. Either handle your exceptions locally and then return your boolean, or throw them and let them bubble up and handle them at the front end.