How to display my own exception?
I'm developing a web project where i need to add custom exception classes. For example, how can i display a message from my custom exception class when the session timeout occurs? Please help. Any sample will be helpful.
This is what i written in my exception class so far:
public class CustomException : Except开发者_开发百科ion
{
private string message;
public CustomException ()
{
this.message = "Invalid Query";
}
public CustomException (String message)
{
this.message = message;
}
}
Need to know how to link this with the session timeout, from where i need to write the logic of the same. Thank You.
If you are looking to throw your custom exception
when the is raised you can do it like this.
try {
DataTable dt = q.ExecuteQuery(); //This throws a timeout.
} catch(SessiontTimeoutException ste) {
throw new CustomException("Session has timed out");
} catch(Exception e) {
//Show unexpected exception has occured
}
Not too sure if this is what you are trying to do.
Update:
To Find out if SqlException is a TimeoutException please see this StackOverFlow Post.
You might want to write this as
public CustomException() : base("Invalid Query") { }
this way the exception message gets passed correctly, for the other constructor
public CustomException(String message) : base(message) { }
then you don't need the private string message field.
SqlException class exposes the property Errors which is a collection of SqlError objects. You can query the Number property of each error object which corresponds to an entry in the master.dbo.sysmessages
table.
I recommend you use Inner Exception
to get user friendly exception message with also the system error message. If getting MyException
, you'll see your exception message and the system exception message at MyException.ToString()
.
Additionally, if you are concerned for coding Exception, you can use the Code Snippet Feature of VS. Just type 'Exception' and press TAB key twice, then VS will create Exception
class as the following code.
try
{
DataTable dt = q.ExecuteQuery(); //This throws a timeout.
}
catch (SessiontTimeoutException ex)
{
throw new MyException("my friendly exception message", ex);
}
[Serializable]
public class MyException : Exception
{
public MyException() { }
public MyException(string message) : base(message) { }
public MyException(string message, Exception inner) : base(message, inner) { }
protected MyException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
精彩评论