C# catch not working (invalid token) [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
public Boolean Delete(Int32 HolidayNo)
{
//provides the functionality for the delete class
//create an instance of the data connection class called MyDatabase
clsDataConnection MyDatabase = new clsDataConnection();
//add the HolidayNo parameter passed to this function to the list of parameters to use in the database
MyDatabase.AddParameter("#HolidayNo", HolidayNo);
//execute the stored procedure in the database
MyDatabase.Execute("sproc_tblHolidays_Delete");
//return value for function
return true;
}
catch
{
return false;
}
}
The catch is saying invalid token. No idea how to fix...
For those curious, I'm making a delete function to delete certain values in my database for University.

Change your code to add a try and then check the exception details for any inner exceptions.
public Boolean Delete(Int32 HolidayNo)
{
try
{
//provides the functionality for the delete class
//create an instance of the data connection class called MyDatabase
clsDataConnection MyDatabase = new clsDataConnection();
//add the HolidayNo parameter passed to this function to the list of parameters to use in the database
MyDatabase.AddParameter("#HolidayNo", HolidayNo);
//execute the stored procedure in the database
MyDatabase.Execute("sproc_tblHolidays_Delete");
//return value for function
return true;
}
catch (Exception ex)
{
return false;
}
}

The reason you're getting an Unexpected Token error is that your catch block is completely outside of your method. Also, you're missing the try portion of the try / catch. To correct this, put the catch block inside your method and put the rest of your code in a try block just before the catch:
public Boolean Delete(Int32 HolidayNo)
{
try
{
clsDataConnection MyDatabase = new clsDataConnection();
MyDatabase.AddParameter("#HolidayNo", HolidayNo);
MyDatabase.Execute("sproc_tblHolidays_Delete");
return true;
}
catch
{
return false;
}
}

I don't even know how that compiled. Please begin by cleaning up your method. Like so:
public Boolean Delete(Int32 HolidayNo)
{
var deleted = false;
try {
if (HolidayNo > 0) {
//provides the functionality for the delete class
//create an instance of the data connection class called MyDatabase
clsDataConnection MyDatabase = new clsDataConnection();
//add the HolidayNo parameter passed to this function to the list of parameters to use in the database
MyDatabase.AddParameter("#HolidayNo", HolidayNo);
//execute the stored procedure in the database
MyDatabase.Execute("sproc_tblHolidays_Delete");
deleted = true;
}
}
catch (Exception ex)
{
// TODO: Log exception ex
return deleted;
}
}

Related

C# how to capture stored procedure exceptions? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Code:
using (var reader = await cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
var recibir = reader.VisibleFieldCount;
var rear = reader;
response.Add(new Cuota
{
opcion = (int)reader["PC_NUMERO_OPCION"],
cuota = (int)reader["PC_NUMERO_CUOTAS"]
});
}
}
I am trying to get the exceptions of SQL Server, what are the corresponding methods?
In general, you can catch a SQL Exception using the SQLException class. It works like this:
try
{
// your code that calls the database here
}
catch (SqlException e)
{
// your code that handles the Sql Exception
}
I typically add a double catch, just in case there is some other error in my code tht isn't SQL related:
try
{
// your code that calls the database here
}
catch (SqlException e)
{
// your code that handles the Sql Exception
}
catch (Exception ex)
{
// your code that handles normal exceptions
}

Catch specific exception instead of "Exception ex" [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm inserting data to a database and I guess some kind of exceptions might occur here, possible more than one?
ussually I used to write something like this:
try
{
//Execution code
}
catch(Exception ex)
{
// log error and throw it
}
And I think it's better to catch some specific exception instead of (Exception ex) something like this:
try
{
// my possibly bad code which inserts data to db
var someEntity = CreateEntityFromDTO(someDTO);
_context.SomeThing.Add(someEntity);
await _context.SaveChangesAsync(cancellationToken);
}
catch(MySpecificException mse)
{
// log error and throw it
}
What might be best practice when it's about catching exception while inserting data to db ?
Thanks
Cheers
You could make your SpecificExceptions inherit from another higher level DatabaseException and handle all Database Exceptions in one catch clause like
public class DatabaseException : Exception {}
public class MySpecificException : DatabaseException {}
public class YetAnotherDBSpecificException : DatabaseException {}
try
{
// insert data.
}
catch(DatabaseException dbEx)
{
// A database exception occured.
Console.Log(dbEx.Message);
}
catch(Exception other)
{
// Non db exception occured.
Console.Log(other.Message);
}

Try Catch to Handle Exception [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am trying to update some documents in DocumentDb / CosmosDb, and if that fails, need to do something else, and then if that fails to log it out...
try {
do a thing w/ database
}
catch (DocumentClientException dce1) {
try {
do another, alternative thing w/ database
}
catch (DocumentClientException dce2) {
log to app insights.
}
}
I'm not sure about this, it seems clunky.. what do you guys think?
For additional bonus points, I need to do this quite frequently.. so something that I can farm off somewhere would be even better ;)
Personally I'd avoid intermixing exception flow with a functional logic flow. It can get brittle. Instead, convert the exception into a logical flag and use it in ordinary logic constructs.
So step 1 is catch the exception and set a variable or return value based on it, and wrap this in an independent method to mask the messiness from everyone else:
bool TryDoSomethingWithDataBase()
{
try
{
//Do thing that could fail
return true;
}
catch(SpecificException ex)
{
return false;
}
}
bool TryDoSomethingElseWithDataBase()
{
try
{
//Do thing that could fail
return true;
}
catch(SpecificException ex)
{
return false;
}
}
Step 2 is to write the logic as usual:
if (!TryDoSomethingWithDatabase())
{
if (!TryDoSomethingElseWithDatabase())
{
LogFatalError();
}
}
Or
var ok = TryDoSomethingWithDatabase();
if (ok) return;
ok = TryDoSomethingElseWithDatabase();
if (ok) return;
LogFatalError();
Why would your thing with the Database fail? You would be better coding for the conditionals you are aware of and expecting and do different things if you want to go into a different logic for processing the result.
Try catch will catch anything and everything, so if your connection to the db fails etc or if you are trying to read or insert malformed data etc.
Try catch does have various exceptions that you can investigate further and catch the specific exception you are interested in.. e.g.
try
//try something
catch (Exception ex)
{
if (ex is FormatException || ex is OverflowException)
{
//Do something specific;
return;
}
throw;
}
This is ok but if you say you'll have this over and over it's better to extract that logic and reuse it.
One way of doing this is to have a method that accept the first and section actions as parameters, for example:
public void TryThis(Action doFirst, Action doSecond)
{
try {
doFirst();
}
catch (DocumentClientException dce1) {
try {
doSecond();
}
catch (DocumentClientException dce2) {
log to app insights.
}
}
}
And then use it like so:
public void DoSomethig1()
{
...
}
public void DoSomething2()
{
...
}
TryThis(DoSomething1, DoSomething2)

C# error "Not all code paths return a value"

I translated this part of the code from vb to c# and giving me this error message. "Not all code paths return a value". What is the problem? Thanks in advance.
public DataSet LoadSearchDataSet(string strConnection, string strSQL)
{
//The purpose of this function is to create and populate a data
//set based on a SQL statement passed in to the function.
try
{
DataSet dsData = new DataSet();
//call the table in the local dataset "results" since the values
//may be coming from multiple tables.
string strTableName = "Results";
bool blnRunStoredProc = false;
dsData = PopulateDataSetTable(strConnection, strTableName, strSQL, blnRunStoredProc, dsData);
WriteSampleDataToOutputWindow(dsData);
//return the data set to the calling procedure
return dsData;
}
catch
{
//error handling goes here
UnhandledExceptionHandler();
}
}
You are missing the return value in the case the code throws an exception.
public DataSet LoadSearchDataSet(string strConnection, string strSQL)
{
//The purpose of this function is to create and populate a data
//set based on a SQL statement passed in to the function.
DataSet dsData = new DataSet();
try
{
//call the table in the local dataset "results" since the values
//may be coming from multiple tables.
string strTableName = "Results";
bool blnRunStoredProc = false;
dsData = PopulateDataSetTable(strConnection, strTableName, strSQL, blnRunStoredProc, dsData);
WriteSampleDataToOutputWindow(dsData);
}
catch
{
//error handling goes here
UnhandledExceptionHandler();
}
//return the data set to the calling procedure
return dsData;
}
If an exception occurs in your try block before the return statement, the catch is executed and that does not return anything, because you did not tell it to.
You can do one of these:
Return a value from the catch block. Do this only if it makes sense and you have a sensible value you can return. Be aware that returning null is a usual source of bugs and there are patterns out there to avoid just that.
Re-throw the exception that occurred, if you cannot do anything at this point about it (and return an object that makes sense). You can do this by adding a line that says: throw;
Throw a different error - You can package the original exception in a new one, providing extra details about the context, if necessary.
You need to add a return statement after your catch clause!
In case of an exception inside your try catch clause, you won't return a value. And that's exactly what your error is indicating.
This is a common error message in functions, as functions are designed to return some value. If your code passes the catch section, it will reach the end of the function without returning anything, thats where you need to return the value.
rewrite like this:
DataSet dsData = null;
try
{
//call the table in the local dataset "results" since the values
//may be coming from multiple tables.
string strTableName = "Results";
bool blnRunStoredProc = false;
dsData = PopulateDataSetTable(strConnection, strTableName, strSQL, blnRunStoredProc, dsData);
WriteSampleDataToOutputWindow(dsData);
}
catch
{
//error handling goes here
UnhandledExceptionHandler();
}
//return the data set to the calling procedure
return dsData;
You can resolve this issue by :
change the function return to VOID (if you does not return something)
give return keyword with variable name before end function
This is because in the case of any exception occurs,the exception will thrown to the catch, in that case the code will not return any value. so you have to return some value from the catch to avoid this issue
Replace the catch with this:
catch
{
//error handling goes here
UnhandledExceptionHandler();
return new DataSet();
}
It is must to return proper value in any case. so try to maintain try catch block with return value or outside of try/catch block if nothing to return in try / catch block.

Annoying SQL exception, probably due to some code done wrong

I started working on this "already started" project, and I'm having a really annoying error when trying to execute some interactions with SQL Server 2008:
The server failed to resume the
transaction. Desc.:
One of these errors I get in this specific method call:
The aspx.cs Call:
busProcesso openProcess = new busProcesso(pProcessoId);
try
{
if (openProcess.GetDocument() == null)
{
//Irrelevant code.
}
}
catch{ //... }
The Business class (relevant part):
public class busProcesso : IbusProcesso
{
public Processo vProcesso { get; set; }
RENDBDataContext db;
public busProcesso()
{
vProcesso = new Processo();
}
public busProcesso(decimal pProcessoId)
{
db = new RENDBDataContext();
try
{
vProcesso = db.Processos.SingleOrDefault(x => x.Id == pProcessoId);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
public string GetDocument()
{
try
{
string document = null;
foreach (Processo_has_Servico ps in ListaServicosProcesso())
{
if (ps.Servico.Document != null) //Get the error right at this line.
{
document = ps.Servico.Document;
}
}
return document ;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
public IQueryable<Processo_has_Servico> ListaServicosProcesso()
{
db = new RENDBDataContext();
try
{
return from ps in db.Processo_has_Servicos
join s in db.Servicos on ps.Servico_Id equals s.Id
where ps.Processo_Id == vProcesso.Id
select ps;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
}
As I said, the error occurs right at the line:
if (ps.Servico.Document != null) from the GetDocument() method.
Opening SQL Server Activity Monitor, I see there is a process for my database (.Net SqlClient Data Provider)
After some time/use (when I start to get the "server failed to resume the transaction" error), I go to the SQL Server Activity Monitor and there's around 5 or 6 more identical processes that weren't killed and (probably) should've been. When I manually kill them, the error stops for a while, until it starts again.
I'm not really good at working in OO and all, so I'm probably missing something, maybe some way to close one of these connections. Also, any help/tip about this structure will be welcome.
PS. The error doesn't happen everytime. Sometimes it runs just perfectly. Then it starts to give the error. Then it stops. Sometimes it happens just once.. pretty weird.
The code in ListaServicosProcesso is creating the context db. Then it is returning an IQueryable.
At this point no request has been sent to the database.
Then there is a for each in the code. At this point EF says "I need to get the data from the database". So it tries to get the data.
But the context db is now out of scope, so it crashes, on the first line that tries to use the data.
There are 2 ways to get around this:
return a list from ListaServicosProcesso, this will force the database call to execute
move the for each into ListaServicosProcesso
Edit
Pharabus is correct db is not out of scope. The problem is here:
db = new RENDBDataContext();
A new instance of the context is being created without the old one being disposed. Try Dispose of db at the end of ListaServicosProcesso. Even better place db in a using statement. But then the foreach must be moved inside the using statement.
Here's a couple of ideas to try.
1/ You can attach SQL server profiler to see the query that is being executed, which will allow you to copy and paste that query to see the data that is in the database. This might be help.
2/ You never check whether ps.Servico is null - you jump straight to ps.Servico.Document. If ps.Servico is null then you will get a null reference exception if you try to access any properties on that object.
I'm not sure of the exact cause of the error you're seeing (if you Google it, the references are all over the place...), but there are a few things you could improve in your code and I've found that just cleaning things up a bit often makes problems go away. Not always, but often.
I agree with the other answerers that it would help to keep better track of your DataContext(s). For example in you're creating it once in the constructor, then again in ListaServicosProcesso(). At that point vProcesso is on one DataContext and other entities will be on another, which gets messy.
I think you could simplify the whole thing a bit, for example you could combine GetDocument() and ListaServicosProcesso() like this:
public string GetDocument()
{
try
{
// Are you sure vProcesso is not null?
if (vProcesso == null)
return null;
// Only create the context if it wasn't already created,
if (db == null)
db = new RENDBDataContext();
return db.Processo_has_Servicos
.Where(ps => ps.Processo_Id == vProcesso.Id && ps.Servico.Document != null)
.Select(ps => ps.Servico.Document) // use an implicit join
.SingleOrDefault();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}

Categories

Resources