473,623 Members | 2,447 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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)
========BASECLA SSEXCEPTION==== ======
[Serializable]
public class TurabsCriticalE xception : ApplicationExce ption
{
Exception t;

public TurabsCriticalE xception() : base()
{
saveExceptionTo File();
}

public TurabsCriticalE xception(string message) : base(message)
{
MessageInternal = message;
saveExceptionTo File();
}

public TurabsCriticalE xception(string message, Exception inner) :
base(message, inner)
{
t = inner;
MessageInternal = message;
saveExceptionTo File();
}

protected TurabsCriticalE xception(Serial izationInfo info, StreamingContex t
context) : base(info,conte xt)
{
m_strMachineNam e = info.GetString( "m_strMachineNa me");
}

public override void GetObjectData(S erializationInf o info, StreamingContex t
context)
{
info.AddValue(" m_strMachineNam e", m_strMachineNam e, typeof(String)) ;
info.AddValue(" m_DateAndTIme", m_DateAndTime,t ypeof(DateTime) );

base.GetObjectD ata (info, context);
}

private string m_strMachineNam e = Environment.Mac hineName;

public string MachineName
{
get{return m_strMachineNam e;}
set{m_strMachin eName = value;}
}
private string m_MessageIntern al = string.Empty;

public string MessageInternal
{get{return m_MessageIntern al;}
set{m_MessageIn ternal = value;}
}
private DateTime m_DateAndTime = DateTime.Now;

public DateTime DateAndTime
{get{return m_DateAndTime;}
set{m_DateAndTi me = value;}
}
protected void saveExceptionTo File()
{
try
{
FileStream fs = new FileStream(@"c: \Exception.txt" , FileMode.OpenOr Create,
FileAccess.Writ e);
StreamWriter m_streamWriter = new StreamWriter(fs );

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

m_streamWriter. WriteLine(Machi neName.ToString ());
m_streamWriter. WriteLine(DateA ndTime.ToShortT imeString());

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

}
}
========DERRIVE DCLASSEXCEPTION ==========
public class TurabsCriticalD atabaseExceptio n : TurabsCriticalE xception
{
public TurabsCriticalD atabaseExceptio n(string message) : base(message)
{

}
}

========TESTCLA SS==========
public class DB
{
}
public int DbStuff()
{
throw new TurabsException s.TurabsCritica lDatabaseExcept ion("Server having
problem!");
}
}

========TESTCOD E==========

DB db = new DB();

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



Nov 15 '05 #1
6 1791
Do not use exceptions to handle expected errors, thats not what theyre for.

Throwing exceptions is expensive, they are for "exceptiona l" 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.c om> wrote in message
news:OO******** ******@TK2MSFTN GP12.phx.gbl...
Hi i just read:
http://msdn.microsoft.com/library/de...us/dnbda/html/
exceptdotnet.as p
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)
========BASECLA SSEXCEPTION==== ======
[Serializable]
public class TurabsCriticalE xception : ApplicationExce ption
{
Exception t;

public TurabsCriticalE xception() : base()
{
saveExceptionTo File();
}

public TurabsCriticalE xception(string message) : base(message)
{
MessageInternal = message;
saveExceptionTo File();
}

public TurabsCriticalE xception(string message, Exception inner) :
base(message, inner)
{
t = inner;
MessageInternal = message;
saveExceptionTo File();
}

protected TurabsCriticalE xception(Serial izationInfo info, StreamingContex t
context) : base(info,conte xt)
{
m_strMachineNam e = info.GetString( "m_strMachineNa me");
}

public override void GetObjectData(S erializationInf o info, StreamingContex t context)
{
info.AddValue(" m_strMachineNam e", m_strMachineNam e, typeof(String)) ;
info.AddValue(" m_DateAndTIme", m_DateAndTime,t ypeof(DateTime) );

base.GetObjectD ata (info, context);
}

private string m_strMachineNam e = Environment.Mac hineName;

public string MachineName
{
get{return m_strMachineNam e;}
set{m_strMachin eName = value;}
}
private string m_MessageIntern al = string.Empty;

public string MessageInternal
{get{return m_MessageIntern al;}
set{m_MessageIn ternal = value;}
}
private DateTime m_DateAndTime = DateTime.Now;

public DateTime DateAndTime
{get{return m_DateAndTime;}
set{m_DateAndTi me = value;}
}
protected void saveExceptionTo File()
{
try
{
FileStream fs = new FileStream(@"c: \Exception.txt" , FileMode.OpenOr Create, FileAccess.Writ e);
StreamWriter m_streamWriter = new StreamWriter(fs );

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

m_streamWriter. WriteLine(Machi neName.ToString ());
m_streamWriter. WriteLine(DateA ndTime.ToShortT imeString());

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

}
}
========DERRIVE DCLASSEXCEPTION ==========
public class TurabsCriticalD atabaseExceptio n : TurabsCriticalE xception
{
public TurabsCriticalD atabaseExceptio n(string message) : base(message)
{

}
}

========TESTCLA SS==========
public class DB
{
}
public int DbStuff()
{
throw new TurabsException s.TurabsCritica lDatabaseExcept ion("Server having problem!");
}
}

========TESTCOD E==========

DB db = new DB();

try
{
db.DbStuff(6);
}
catch(TurabsCri ticalException 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 "exceptiona l" 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 customException s were to common. But
anyway. IF i get a critical exeption, lets say i suddenly cant access my
"Userinfo.t xt" 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.c om> wrote in message
news:OO******** ******@TK2MSFTN GP12.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.co m
says...
IF i get a critical exeption, lets say i suddenly cant access my
"Userinfo.t xt" 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
baseCustomExcep tions and is just inhireted and is not override in the
derived CustomException s. 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(SqlExcept ion sqlex)
{
MyCustomDatabas eException = 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
4615
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 name="Exceptions"> <destinations> <destination name="Event Log Destination" sink="Event Log Sink" format="Text Formatter" /> </destinations> </category>
12
1424
by: Mark | last post by:
Apologies for the lengthy posting.... In a previous posting: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=3fb3728b%240%2422605%24cc9e4d1f%40news.dial.pipex.com&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3D3fb3728b%25240%252422605%2524cc9e4d1f%2540news.dial.pipex.com I asked a question about how to ensure that some "tidying up" code would be run at the end of a Method independently of where...
44
4206
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 user tasks should always be included in a try/catch block that actually handles any exceptions that occur (log the exception, display a message box, etc.). 2. Low-level operations that are used to carry out the high level tasks
1
1402
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 DLL's.
15
2709
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
1828
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 ????? OK, this function may return a boolean, and if this is true, then no message back is really required, but if it fails then some supporting message needs to be returned to the calling code. As I see it there are a few options.
10
1496
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 catch(Exception) then every exception will also be caught. These two will catch the exact same exception is this right understod?
3
3397
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 exception constructors? I've noticed that, f.ex., ArgumentException accepts null arguments without raising ArgumentNullException. Obviously, if nothing is to be supplied to the exception constructor, the default constructor should
1
1031
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, wrap the corresponding SQL statements. My question is would it better to let any exceptions thrown by the underlying DB-API calls bubble up from these methods, or should I catch them inside the methods, wrap them inside my own custom exceptions,...
0
8168
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8672
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8614
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8471
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6107
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4075
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4167
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2603
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1474
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.