Using MySqlDataReader, I try to read a primary key which is int(11). int id=reader.GetInt32(0); gives the error "Object must implement IConvertible". What is the reason? How can I fix it?
reader.GetInt32(0) will accept the argument as columnIndex this will throw exceptions as like the following :credits to MSDN
you can trace out the error using :
while (reader.Read())
{
if (reader.IsDBNull(2))
{
Console.Write("<NULL>");
}
else
{
try
{
Console.Write(reader.GetInt32(2));
}
catch (InvalidCastException)
{
Console.Write("Invalid data type.");
}
}
Console.WriteLine();
}
Related
How to catch that there is an error from CommandLineParser so I can return my own error codes?
I need to return my own codes when my console application is called from say SSIS.
class Program
{
static void Main(string[] args)
{
try
{
var myParserResult = Parser.Default.ParseArguments<UploadFileCommand, DownloadFileCommand, CompressFileCommand>(args)
.WithParsed<ICommand>(t => t.Execute());
var parsed = myParserResult as NotParsed<object>;
if (parsed != null && parsed.Errors.Any())
{
Console.WriteLine("Has Errors");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
The method ParseArguments() will return a ParserResult<T> object to indicate if the parsing was successful or not. In case the parsing was not successful a NotParsed<T> instance is returned. This class has an Errors property to contain all the Error instances why the parsing failed. You can use it in a normal foreach() loop to iterate over the found errors:
ParserResult<Options> result = parser.ParseArguments<Options>(args);
Console.WriteLine(result);
NotParsed<Options> notParsed = result as NotParsed<Options>;
if (notParsed != null)
{
foreach (var error in notParsed.Errors)
{
Console.WriteLine(error);
}
}
This might print the following debug output:
CommandLine.NotParsed`1[Testing.Options]
CommandLine.UnknownOptionError
CommandLine.UnknownOptionError
I'm making a Tic-Tac-Toe game for an assignment and I am new to C#. I have a custom exception for bad moves called BadMoveException, which would be if the user enters anything other than 0-8. There is existing code for the assignment and I'm wondering if I should do away with the code to create my own to use this exception or if it is easy enough to implement here? Here is the code:
string input;
int position;
do
{
input = Console.ReadLine();
}
while (!int.TryParse(input, out position));
I need to catch the BadMoveException, and any others with an unknown error message. Thank you in advance!
As long as your BadMoveException inherits from Exception, then you can use it just like any other Exception, like this:
try {
//do stuff
if (badMove) {
throw new BadMoveException();
}
} catch (BadMoveException) {
//user made a bad move!!
} catch {
//something else went wrong
}
There is more information about exception handling here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/
Here's what I have:
1- First, your exception need to inherit from Exception like this:
public class BadMoveException : Exception { // Your code here }
2- When you have an error, you use it like this:
throw new BadMoveException(// Enter parameter if you have any in you class);
And you catch it:
try
{
if(Position < 0 || Position > 8)
{
throw new BadMoveException(// Enter parameter here if you have any);
}
else
{
// Your code here
}
}
catch(BadMoveException bmex) { // Show message here }
catch(Exception ex) { // Show other exception }
Hope it helps !
Links for documentation: http://www.tutorialsteacher.com/csharp/custom-exception-csharp
https://stackify.com/csharp-exception-handling-best-practices/
I'm using wcf Service to insert data to DB and my service crashes saying exception un-handled. I'm trying to pass on exception from one WCF service method to other WCF method and from there throwing exception to client.
Here is My code:
Data Inserting Method of WCF Service: method to insert data to DB
public int insertStatements(SqlCommand cmd)
{
Try
{
//insert data to the db
}
catch(SqlException ex)
{
if (ex.Number == 2627) // if unique key constraint error
{
throw new FaultException( "error reason", new FaultCode("Error Code: ");
}
else
{
throw new FaultException("DB error: ", new FaultCode("Error Code: " +);
}
}
catch (FaultException ex)
{
throw new FaultException("Unknown Error",new FaultCode("Unknown Error"));
}
}
WCF Insert location method, which is service exposed method(Public)
public int insertLocation (string name)
{
try
{
// this method communicates with client
dataconnection.insertStatements(cmd);
}
catch
{
throw; // Here i'm getting error
}
}
in my client: winform Application
try
{
AreaDataServicesClient DataObject = new AreaDataServicesClient("BasicHttpBinding_IAreaDataServices");
int rowsAffected = DataObject.InsertProvince(ProvinceObject.AreaName, ProvinceObject.AreaKm);
return rowsAffected;
}
catch(FaultException ex)
{
messagebox.show("erro occured");
}
This is the Error i get:
"An exception of type 'System.ServiceModel.FaultException' occurred in EMSDataServices.dll but was not handled in user code"
Why service method does not pass exception to the client.
i found it. There was nothing wrong with the code. i was running the services on debug mode and in exception setting 'break at this point if user code is unhandled' was checked,so it was stopping the service to perform further action and client was crashing due to no response from service.
i unchecked it and it works as expected.
#Mohsin, catch (FaultException ex) in insertStatements is useless. It will never catch your exception. because you are throwing the exception outside the method. You should handle the exception somewhere which is re-thrown. That you can do it in the insertLocation method. See the bellow modified code.
public int insertLocation(string name)
{
try
{
dataconnection.insertStatements(cmd);
}
catch (FaultException ex)
{
// you should handle the exception here. Do not retrow here too. Otherwise you may need to handle somewhere else again.
}
}
public int insertStatements(SqlCommand cmd)
{
try
{
//insert data to the db
}
catch (SqlException ex)
{
if (ex.Number == 2627) // if unique key constraint error
{
throw new FaultException("error reason", new FaultCode("Error Code: ");
}
else
{
throw new FaultException("DB error: ", new FaultCode("Error Code: ");
}
}
}
The line marked ///Here i'm getting the error is a throw statement. That's exactly what it's supposed to do. It's taking the exception which has been caught (because it's in a try) and making it unhandled again, as if it had never been caught.
That's what you might do if you wanted to log or inspect the exception and then let it bubble up. In this case it's exactly the same as removing the entire try/catch.
This:
public int insertLocation (string name)
{
try
{
dataconnection.insertStatements(cmd);
}
catch
{
throw; // Here i'm getting error
}
}
is the same as this:
public int insertLocation (string name)
{
dataconnection.insertStatements(cmd);
}
I would like to know which is the best way to make a Exception treatment, because inside my Try statement, I have a lot of validations, and if I get some Exception there, my Catch statement can tell me what happens, but how could I know in which field occurs the Exception ?
Sample Code
try
{
// If I get a Exception when converting to number,
// I will understand the error
// but how could I know where in my `Try` statement was the error ?
int valor = Convert.ToInt32(xmlnode[i].ChildNodes.Item(2).InnerText.Trim());
// A Lot of another validations here
}
Catch(Exception e)
{
this.LogInformation(e.Message);
}
Best practises would be not to use Try-Catch at all when you convert strings to numbers. Therefore you should use the TryParse methods like int.TryParse.
// note that here is also a possible error-source
string valorToken = xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
int valor;
if(!int.TryParse(valorToken, out valor))
{
// log this
}
// else valor was parsed correctly
Apart from that, if you want to provide exact error messages you have to use multiple try-catch or handle different exception types (the most general Exception type must be the last).
Don't use Convert.ToInt32 if you're unsure of the value. Use Int32.TryParse instead:
int valor;
if (Int32.TryParse(xmlnode[i].ChildNodes.Item(2).InnerText.Trim(), out valor))
{
// Worked! valor contains value
}
else
{
// Not a valid Int32
}
In addition you should not be using Exceptions to catch validation errors. Your validation code should calculate if the value is correct, rather than failing when it isn't. A validation class should expect to receive both valid and invalid data as input. Because you expect invalid input you should not be catching exceptions when it's invalid.
Come up with a test that checks if the data is valid and return true or false. Pretty much all numeric types have a TryParse method like the above. For your custom rules for other validation methods come up with a specification that defines exactly what valid and invalid input is and then write a method to implement that specification.
Move try..catch inside loop. Thus you will know which item exactly caused exception
foreach(var xmlNode in nodes)
{
try
{
//
int valor = Convert.ToInt32(xmlNode.ChildNodes.Item(2).InnerText.Trim());
// A Lot of another validations here
}
catch(Exception e)
{
LogInformation(e.Message); // current item is xmlNode
return;
}
}
If there is even the remotest possibility that the value you're tring to parse will not be parsable, it is therefore not an exceptional circumstance, vis. should not be treated as an exception.
In this case, there is TryParse, which allows you to determine that the value is not valid for parsing:
int valor;
if(int.TryParse(xmlnode[i].ChildNodes.Item(2).InnerText.Trim(), out valor))
{
// "valor" is sucessfully parsed
}
else
{
// invalid parse - do something with that knowledge
}
Unless its different Exceptions that get created (i.e. different classes) then you will need to handle this with different try catches.
Typically you can do:
try
{
// If I get a Exception when converting to number,
// I will understand the error
// but how could I know where in my `Try` statement was the error ?
int valor = Convert.ToInt32(xmlnode[i].ChildNodes.Item(2).InnerText.Trim());
// A Lot of another validations here
}
Catch(IOException ioe) {
// Handle, log
}
Catch(ArgumentNullException ane) {
// Handle, log
}
Catch(Exception e)
{
// Handle, log and potentially rethrow
}
You could also have individual try catches (which is kind of what most people would do I think) or nested try catches in your try block:
Like
// First block
try {
// Convert here once
} catch (Exception ex) {
// Handle and log
}
// Second block
try {
// Convert here once
} catch (Exception ex) {
// Handle and log
}
Not sure if that helps at all.
try
{
}
catch (Exception ex)
{
var stackTrace = new StackTrace(ex, true);
var frame = stackTrace.GetFrame(0);
var line = frame.GetFileLineNumber();
var method = frame.GetMethod();
}
try
{
// call to Com Method
}
catch (COMException e)
{
if (e.ErrorCode == 0x80040154) // REGDB_E_CLASSNOTREG.
{
// handle this error.
}
}
I would like to check if com exception is thrown due to REGDB_E_CLASSNOTREG then handle it. I tried with the code above but it gives warning:
Comparison to integral constant is useless; the constant is outside the range of type 'int'
I believe this error is due to 0x80040154 is not in Int32 range.
Can you suggest any possible solution? or Is there any other way to check this?
Use the unchecked keyword:
catch (COMException ex) {
if (ex.ErrorCode == unchecked((int)0x80040514)) {
//...
}
}
Comparing with its integer equivalent works fine:
if (e.ErrorCode == -2147287036) // REGDB_E_CLASSNOTREG.
{
// handle this error.
}
You can also try by using some text that is displayed in Exception message/Error Message like follows
try
{
// call to Com Method
}
catch (COMException e)
{
if (e.ToString().Contains("Your Error Text here")) // REGDB_E_CLASSNOTREG.
{
// handle this error.
}
}