473,327 Members | 1,952 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

Question about Custom Exceptions

Hi i just read:
http://msdn.microsoft.com/library/de...ceptdotnet.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.ToShortTimeSt ring());

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
}



Nov 15 '05 #1
6 1777
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" <pl*@askforit.com> wrote in message
news:OO**************@TK2MSFTNGP12.phx.gbl...
Hi i just read:
http://msdn.microsoft.com/library/de...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.ToShortTimeSt ring());

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
}


Nov 15 '05 #2
> 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
Nov 15 '05 #3
> Do not use exceptions to handle expected errors, thats not what theyre for.

What made you think the OP was doing this?

--
Michael Culley
Nov 15 '05 #4
"Flare" <pl*@askforit.com> wrote in message
news:OO**************@TK2MSFTNGP12.phx.gbl...
Hi i just read:
http://msdn.microsoft.com/library/de...ceptdotnet.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/de...ml/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
--
http://www.csharp-station.com
Nov 15 '05 #5
In article <e0*************@TK2MSFTNGP10.phx.gbl>, pl*@askforit.com
says...
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/de...l=/library/en-
us/dnbda/html/emab-rm.asp

(Watch for wrap)

-- Rick

Nov 15 '05 #6
> 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
Nov 15 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Steven | last post by:
I just downloaded the June 2005 release and I want to set up basic logging to log problems such as exceptions. I have created a category named Exceptions with the following: <category...
12
by: Mark | last post by:
Apologies for the lengthy posting.... In a previous posting:...
44
by: craig | last post by:
I am wondering if there are some best practices for determining a strategy for using try/catch blocks within an application. My current thoughts are: 1. The code the initiates any high-level...
1
by: leodippolito | last post by:
Hello, I have these entities in my ASP.NET application: - data access layer (DATA) - custom exception class (EXCEPTION) - cache management class (CACHE) They're all built into different...
15
by: bill salkin | last post by:
I'd like to create a custom error handler like this in VB.NET: .... try ... Throw ("Lender Name not in table") .... catch ("Lender Name not in table")
14
by: Mr Newbie | last post by:
I am often in the situation where I want to act on the result of a function, but a simple boolean is not enough. For example, I may have a function called isAuthorised ( User, Action ) as ?????...
10
by: tony | last post by:
Hello!! As you know every user defined exception must be derived from class Exception. Now to my question if I write catch then every exception will be caught. If I instead write...
3
by: matko | last post by:
This is a long one, so I'll summarize: 1. What are your opinions on raising an exception within the constructor of a (custom) exception? 2. How do -you- validate arguments in your own...
1
by: asincero | last post by:
I have a class called Users that provides a higher level of abstraction to an underlying "users" table in a pgsql database. It has methods like "addUser()" and "deleteUser()" which, obviously,...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.