Reputation: 467
I want to throw an SqlException
Number from one class into a regular Exception
in another.
So I want something like this (pseudo code)
SQL Class
catch (SqlException sqlex)
{
if (sqlex.Number == 911)
{
throw new Exception("There is no database to be found");
}
if (sqlex.Number == 1510)
{
throw new Exception("There isn't a database attached");
}
if (sqlex.Number == 5120)
{
throw; //("You do not have permissions to attach this file.");
}
else
{
throw sqlex;
}
}
Class B
if (ex == 5120)
{
dostuff();
}
The 'dirty' way around it is that I could just throw a new Exception
with the message "5120" and then read it from there but I don't think that's the best way?
Thanks,
Upvotes: 4
Views: 189
Reputation: 13676
Normally, code that could potentially throw an exception is wrapped with try{} catch{}
block on a next layer and this is combined with custom Exceptions. For possible multiple exceptions you can use multiple catch blocks:
public class NoPermissionSqlException : Exception
{
public NoPermissionSqlException(string message) : base(message) {}
// ... implement other constructors
}
And use it :
public void MyMethod() // method that could throw an exception
{
if (sqlex.Number == 5120)
{
throw new NoPermissionSqlException("You do not have permissions to attach this file.");
}
}
And calling code:
try
{
MyMethod();
}
catch(NoPermissionSqlException ex)
{
// ... handle no permission error here
dostuff();
}
catch(Exception ex)
{
// ... default handler
}
Upvotes: 2