Question about Custom Exceptions

F

Flare

Hi i just read:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/exceptdotnet.asp

Wich is interesting reading by the way.

But. I have'nt used exception very much to anything else than ordinary
FileExeptions etc. Now i want to create my own exception hierarchy.

I want to do this so that i can log the exceltion information to a file or a
database. Doesent mather right now.

But I can't Figure out where to put the loggin rutine after reading the
article. I suggest that i make a baseexception, wich i Iseriazable
compliant. I have done that. But is it in my Baseclass exception that i
sjould implement my loggin routine?

Or is it in my derrived Custom Exception? Or should the logging rutine be in
a seperate class wich i call when i Catch one of my Cusotm Exceptions?

I have made this so far, but stopped because i have doubt that it s the way
to go.

THX in reagards if someone can clear out for me how to create custom
exceptions wich can be logged. (See sample code i have made)
Anders, Denmark

(Some Sample code)
========BASECLASSEXCEPTION==========
[Serializable]
public class TurabsCriticalException : ApplicationException
{
Exception t;

public TurabsCriticalException() : base()
{
saveExceptionToFile();
}

public TurabsCriticalException(string message) : base(message)
{
MessageInternal = message;
saveExceptionToFile();
}

public TurabsCriticalException(string message, Exception inner) :
base(message, inner)
{
t = inner;
MessageInternal = message;
saveExceptionToFile();
}

protected TurabsCriticalException(SerializationInfo info, StreamingContext
context) : base(info,context)
{
m_strMachineName = info.GetString("m_strMachineName");
}

public override void GetObjectData(SerializationInfo info, StreamingContext
context)
{
info.AddValue("m_strMachineName", m_strMachineName, typeof(String));
info.AddValue("m_DateAndTIme", m_DateAndTime,typeof(DateTime));

base.GetObjectData (info, context);
}

private string m_strMachineName = Environment.MachineName;

public string MachineName
{
get{return m_strMachineName;}
set{m_strMachineName = value;}
}
private string m_MessageInternal = string.Empty;

public string MessageInternal
{get{return m_MessageInternal;}
set{m_MessageInternal = value;}
}
private DateTime m_DateAndTime = DateTime.Now;

public DateTime DateAndTime
{get{return m_DateAndTime;}
set{m_DateAndTime = value;}
}


protected void saveExceptionToFile()
{
try
{
FileStream fs = new FileStream(@"c:\Exception.txt" , FileMode.OpenOrCreate,
FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);

m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine("===== EXCEPTION LOG FILE ======");

m_streamWriter.WriteLine(MachineName.ToString());
m_streamWriter.WriteLine(DateAndTime.ToShortTimeString());

m_streamWriter.Flush();
fs.Close();
}
catch(Exception ex)
{
string e = ex.Message;
//Write to the System log instead
}
finally
{

}
}
========DERRIVEDCLASSEXCEPTION==========
public class TurabsCriticalDatabaseException : TurabsCriticalException
{
public TurabsCriticalDatabaseException(string message) : base(message)
{

}
}

========TESTCLASS==========
public class DB
{
}
public int DbStuff()
{
throw new TurabsExceptions.TurabsCriticalDatabaseException("Server having
problem!");
}
}

========TESTCODE==========

DB db = new DB();

try
{
db.DbStuff(6);
}
catch(TurabsCriticalException ex)
{
// EXCEPTION HAS BEEN WRITTEN TO FILE
}
 
M

Mr.Tickle

Do not use exceptions to handle expected errors, thats not what theyre for.

Throwing exceptions is expensive, they are for "exceptional" cases. not
error handling per se.

So if you need to check a status of a method call, check its return value or
whatever and proceed on that, do not wait for an exception then deal with
it. Thats bad programming and not what exceptions are for.



Flare said:
Hi i just read:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/
exceptdotnet.asp

Wich is interesting reading by the way.

But. I have'nt used exception very much to anything else than ordinary
FileExeptions etc. Now i want to create my own exception hierarchy.

I want to do this so that i can log the exceltion information to a file or a
database. Doesent mather right now.

But I can't Figure out where to put the loggin rutine after reading the
article. I suggest that i make a baseexception, wich i Iseriazable
compliant. I have done that. But is it in my Baseclass exception that i
sjould implement my loggin routine?

Or is it in my derrived Custom Exception? Or should the logging rutine be in
a seperate class wich i call when i Catch one of my Cusotm Exceptions?

I have made this so far, but stopped because i have doubt that it s the way
to go.

THX in reagards if someone can clear out for me how to create custom
exceptions wich can be logged. (See sample code i have made)
Anders, Denmark

(Some Sample code)
========BASECLASSEXCEPTION==========
[Serializable]
public class TurabsCriticalException : ApplicationException
{
Exception t;

public TurabsCriticalException() : base()
{
saveExceptionToFile();
}

public TurabsCriticalException(string message) : base(message)
{
MessageInternal = message;
saveExceptionToFile();
}

public TurabsCriticalException(string message, Exception inner) :
base(message, inner)
{
t = inner;
MessageInternal = message;
saveExceptionToFile();
}

protected TurabsCriticalException(SerializationInfo info, StreamingContext
context) : base(info,context)
{
m_strMachineName = info.GetString("m_strMachineName");
}

public override void GetObjectData(SerializationInfo info, StreamingContext
context)
{
info.AddValue("m_strMachineName", m_strMachineName, typeof(String));
info.AddValue("m_DateAndTIme", m_DateAndTime,typeof(DateTime));

base.GetObjectData (info, context);
}

private string m_strMachineName = Environment.MachineName;

public string MachineName
{
get{return m_strMachineName;}
set{m_strMachineName = value;}
}
private string m_MessageInternal = string.Empty;

public string MessageInternal
{get{return m_MessageInternal;}
set{m_MessageInternal = value;}
}
private DateTime m_DateAndTime = DateTime.Now;

public DateTime DateAndTime
{get{return m_DateAndTime;}
set{m_DateAndTime = value;}
}


protected void saveExceptionToFile()
{
try
{
FileStream fs = new FileStream(@"c:\Exception.txt" , FileMode.OpenOrCreate,
FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);

m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine("===== EXCEPTION LOG FILE ======");

m_streamWriter.WriteLine(MachineName.ToString());
m_streamWriter.WriteLine(DateAndTime.ToShortTimeString());

m_streamWriter.Flush();
fs.Close();
}
catch(Exception ex)
{
string e = ex.Message;
//Write to the System log instead
}
finally
{

}
}
========DERRIVEDCLASSEXCEPTION==========
public class TurabsCriticalDatabaseException : TurabsCriticalException
{
public TurabsCriticalDatabaseException(string message) : base(message)
{

}
}

========TESTCLASS==========
public class DB
{
}
public int DbStuff()
{
throw new TurabsExceptions.TurabsCriticalDatabaseException("Server having
problem!");
}
}

========TESTCODE==========

DB db = new DB();

try
{
db.DbStuff(6);
}
catch(TurabsCriticalException ex)
{
// EXCEPTION HAS BEEN WRITTEN TO FILE
}
 
F

Flare

Do not use exceptions to handle expected errors, thats not what theyre
for.
Throwing exceptions is expensive, they are for "exceptional" cases. not
error handling per se.

So if you need to check a status of a method call, check its return value or
whatever and proceed on that, do not wait for an exception then deal with
it. Thats bad programming and not what exceptions are for.

Thx for your reply. Ok i follow you. My customExceptions were to common. But
anyway. IF i get a critical exeption, lets say i suddenly cant access my
"Userinfo.txt" file. That is critical. This exception i want to log to a
database. I want to do it in an generic way, (i will have other exceptions
would i would want to log). How do I do this, (maybe in regard to the way
the <link> suggests) ?

Thx in reagrds, and for quick answere.
Anders
 
M

Michael Culley

Do not use exceptions to handle expected errors, thats not what theyre for.

What made you think the OP was doing this?
 
J

Joe Mayo

Flare said:
Hi i just read:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/exceptdotnet.asp

Wich is interesting reading by the way.

But. I have'nt used exception very much to anything else than ordinary
FileExeptions etc. Now i want to create my own exception hierarchy.

I want to do this so that i can log the exceltion information to a file or a
database. Doesent mather right now.

But I can't Figure out where to put the loggin rutine after reading the
article. I suggest that i make a baseexception, wich i Iseriazable
compliant. I have done that. But is it in my Baseclass exception that i
sjould implement my loggin routine?

Or is it in my derrived Custom Exception? Or should the logging rutine be in
a seperate class wich i call when i Catch one of my Cusotm Exceptions?

Hi Anders,

Here's another good example:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/emab-rm.asp

Considering your idea about having a logging routine in your exception, I'm
not sure that I would do it that way. My initial thoughts are that if you
wanted truly reusable exceptions, then a single logging method ties you down
to whatever the first implementation was that you came up with. This means
that in the future, if you changed the way you log you would also have to
change the code for all the custom exceptions. You've also taken some of
the control away from potential exception handlers for how to handle the
exception. For instance, an error in one context may simply be handled as a
warning in another. So, if you have a generic logging mechanism, what will
it mean when you look at the log for debugging?

My approach is to look at how the application is built and handle exceptions
as appropriate for that application. This means that when an exception is
raised and caught in one of my handlers, I make the decision in the handler
as to how the exception should be logged.

Joe
 
G

Guinness Mann

IF i get a critical exeption, lets say i suddenly cant access my
"Userinfo.txt" file. That is critical. This exception i want to log to a
database. I want to do it in an generic way, (i will have other exceptions
would i would want to log). How do I do this, (maybe in regard to the way
the <link> suggests) ?

Microsoft has something called the Microsoft Exception Management
Application Block which may be exactly what you're looking for.

Check it out here:

http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/dnbda/html/emab-rm.asp

(Watch for wrap)

-- Rick
 
F

Flare

Considering your idea about having a logging routine in your exception,
I'm
not sure that I would do it that way. My initial thoughts are that if you
wanted truly reusable exceptions, then a single logging method ties you down
to whatever the first implementation was that you came up with. This means
that in the future, if you changed the way you log you would also have to
change the code for all the custom exceptions. You've also taken some of
the control away from potential exception handlers for how to handle the
exception. For instance, an error in one context may simply be handled as a
warning in another. So, if you have a generic logging mechanism, what will
it mean when you look at the log for debugging?

My approach is to look at how the application is built and handle exceptions
as appropriate for that application. This means that when an exception is
raised and caught in one of my handlers, I make the decision in the handler
as to how the exception should be logged.

I have thougt about making a public log(Exception) function wich can be
called when the Exeption is caught. That would prevent loging wehn not
nesecary.

Heres a situations I imagine. The log mechanisme is inside my
baseCustomExceptions and is just inhireted and is not override in the
derived CustomExceptions. I also want to rethrow the customExceptin to give
the user a better error. (Is is sent over a webservice, and so will again be
retrown as SoapException, but enough about that)

try
{
///Connect to SQL server.
///Server room burnt down so exception i trown.
}
catch(SqlException sqlex)
{
MyCustomDatabaseException = new cusEx();
cusEx.Log(sqlex);
throw sqlex(cusEx);
}

Is that stupid?

Reagrds
Anders
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top