16

Can following code be considered as a good practice? If not, why?

try
{
    // code that can cause various exceptions...
}
catch (Exception e)
{
    throw new MyCustomException("Custom error message", e);
}
matori82
  • 3,669
  • 9
  • 42
  • 64
  • Looks ok to me - sometimes you don't care if it's a IO exception or a timeout or what have you, you just want to catch any errors and throw a general 'something went wrong' error and wrap the actual exception - just as you have. – Charleh Feb 03 '14 at 15:27
  • The purists would probably lynch you - but I think it depends on the scenario. For example, are you developing a library which will be used by other code or are you talking about an application, where not doing this leads to a "Application has stopped working" message, rather than a sensible "Could not connect to server" message that the user could do something with – JohnL Feb 03 '14 at 15:30
  • If you are going to do this then be *very* careful not to do this: `catch (Exception e) { new MyCustomException("Custom error message", e); }` Whoops! – Eric Lippert Apr 30 '14 at 22:30

14 Answers14

34

Short answer: Don't do this unless there is some reason that you must. Instead, catch specific exceptions you can deal with at the point you can deal with them, and allow all other exceptions to bubble up the stack.


TL;DR answer: It depends what you're writing, what is going to be calling your code, and why you feel that you need to introduce a custom exception type.

The most important question to ask, I think, is if I catch, what benefit does my caller get?

  • Do not hide information that your caller needs
  • Do not require your caller to jump through any more hoops than necessary

Imagine you're processing a low-level data source; maybe you're doing some encoding or deserialisation. Our system is nice and modular, so you don't have much information about what your low-level data source is, or how your code is being called. Maybe your library is deployed on a server listening to a message queue and writing data to disk. Maybe it's on a desktop and the data is coming from the network and being displayed on a screen.

There are lots of varied exceptions that might occur (DbException, IOException, RemoteException, etc), and you have no useful means of handling them.

In this situation, in C#, the generally accepted thing to do is let the exception bubble up. Your caller knows what to do: the desktop client can alert the user to check their network connection, the service can write to a log and allow new messages to queue up.

If you wrap the exception in your own MyAwesomeLibraryException, you've made your caller's job harder. Your caller now needs to:-

  • Read and understand your documentation
  • Introduce a dependency on your assembly at the point they want to catch
  • Write extra code to interrogate your custom exception
  • Rethrow exceptions they don't care about.

Make sure that extra effort is worth their time. Don't do it for no reason!

If the main justification for your custom exception type is so that you can provide a user with friendly error messages, you should be wary of being overly-nonspecific in the exceptions you catch. I've lost count of the number of times - both as a user and as an engineer - that an overzealous catch statement has hidden the true cause of an issue:-

try
{
  GetDataFromNetwork("htt[://www.foo.com"); // FormatException?

  GetDataFromNetwork(uriArray[0]); // ArrayIndexOutOfBounds?

  GetDataFromNetwork(null); // ArgumentNull?
}
catch(Exception e)
{
  throw new WeClearlyKnowBetterException(
    "Hey, there's something wrong with your network!", e);
}

or, another example:-

try
{
  ImportDataFromDisk("C:\ThisFileDoesNotExist.bar"); // FileNotFound?

  ImportDataFromDisk("C:\BobsPrivateFiles\Foo.bar"); // UnauthorizedAccess?

  ImportDataFromDisk("C:\NotInYourFormat.baz"); // InvalidOperation?

  ImportDataFromDisk("C:\EncryptedWithWrongKey.bar"); // CryptographicException?
}
catch(Exception e)
{
  throw new NotHelpfulException(
    "Couldn't load data!", e); // So how do I *fix* it?
}

Now our caller has to unwrap our custom exception in order to tell the user what's actually gone wrong. In these cases, we've asked our caller to do extra work for no benefit. It is not intrinsically a good idea to introduce a custom exception type wrapping all exceptions. In general, I:-

  1. Catch the most specific exception I can

  2. At the point I can do something about it

  3. Otherwise, I just let the exception bubble up

  4. Bear in mind that hiding the details of what went wrong isn't often useful

That doesn't mean you should never do this!

  1. Sometimes Exception is the most specific exception you can catch because you want to handle all exceptions in the same way - e.g. Log(e); Environment.FailFast();

  2. Sometimes you have the context to handle an exception right at the point where it gets thrown - e.g. you just tried to connect to a network resource and you want to retry

  3. Sometimes the nature of your caller means that you cannot allow an exception to bubble up - e.g. you're writing logging code and you don't want a logging failure to "replace" the original exception that you're trying to log!

  4. Sometimes there's useful extra information you can give your caller at the point an exception is thrown that won't be available higher up the call stack - e.g. in my second example above we could catch (InvalidOperationException e) and include the path of the file we were working with.

  5. Occasionally what went wrong isn't as important as where it went wrong. It might be useful to distinguish a FooModuleException from a BarModuleException irrespective of what the actual problem is - e.g. if there's some async going on that might otherwise prevent you usefully interrogating a stack trace.

  6. Although this is a C# question, it's worth noting that in some other languages (particularly Java) you might be forced to wrap because checked exceptions form part of a method's contract - e.g. if you're implementing an interface, and the interface doesn't specify that the method can throw IOException.

This is all pretty general stuff, though. More specifically to your situation: why do you feel you need the custom exception type? If we know that, we can maybe give you some better tailored advice.

Community
  • 1
  • 1
Iain Galloway
  • 18,669
  • 6
  • 52
  • 73
  • 2
    Thanks for the thorough answer. Let's say there is a part of application that wants to perform action X and all the calling code cares is whether this action succeeds or not. It doesn't care what exact error is. For example, I want to load text from file c:\TEST.TXT and if that's not possible (for whatever reason) then use default hardcoded text. So if file can't be loaded then I don't care about the exact reason (eg. file doesn't exists, permission denied, file content is binary and not ascii...), all I care about is whether action succeeded or not. Is it ok then to use OP code in this case? – matori82 Apr 28 '14 at 10:50
  • If you *genuinely don't care* then sure, go ahead. Beware, though, because there's a whole class of bugs (e.g. any code error that causes a null reference) that could occur inside your `try` that are going to be impossible to find now because of your `catch`. If this application is going anywhere other than your machine you'll probably want to at least log the exception somewhere so you can find out why the operation is failing when you expect it to succeed. – Iain Galloway Apr 30 '14 at 07:44
  • 2
    Knowing whether or how to handle an exception generally requires knowing *where* it occurred; wrapping provides that information. It also requires knowing whether the fact that an exception was thrown has created any new problems beyond those which caused the original exception. Wrapping can sometimes provide that too. If a method's contract specifies that it throws some particular type of exception in some particular circumstance the caller might expect, but it calls a method which happens to throws that same type of exception for some unexpected reason, failing to wrap the exception... – supercat May 27 '14 at 21:52
  • ...may cause the caller to erroneously believe that the exception was thrown for the reason the caller was expecting. – supercat May 27 '14 at 21:52
7

There's an excellent blog post by Eric Lippert, "Vexing exceptions". Eric answers your question with some universal guidelines. Here is a quote from the "sum up" part:

  • Don’t catch fatal exceptions; nothing you can do about them anyway, and trying to generally makes it worse.
  • Fix your code so that it never triggers a boneheaded exception – an "index out of range" exception should never happen in production code.
  • Avoid vexing exceptions whenever possible by calling the “Try” versions of those vexing methods that throw in non-exceptional circumstances. If you cannot avoid calling a vexing method, catch its vexing exceptions.
  • Always handle exceptions that indicate unexpected exogenous conditions; generally it is not worthwhile or practical to anticipate every possible failure. Just try the operation and be prepared to handle the exception.
FreeAsInBeer
  • 12,937
  • 5
  • 50
  • 82
noseratio
  • 59,932
  • 34
  • 208
  • 486
  • 2
    Just to aid for searches - the URL for that blog is no longer valid - but is here: https://ericlippert.com/2008/09/10/vexing-exceptions/ (it may be old, but I think it's still one of the best ways of categorizing different types of exceptions and talking about how an app's handling of them should be different). – DotNetSparky May 31 '21 at 02:26
  • 1
    @DotNetSparky Thanks. I've updated the link. – FreeAsInBeer Sep 12 '22 at 13:23
5

No, generally, you should not do that: this may mask the real exception, which may indicate programming issues in your code. For example, if the code inside the try / catch has a bad line that causes an array index out of bound error, your code would catch that, too, and throw a custom exception for it. The custom exception is now meaningless, because it reports a coding issue, so nobody catching it outside your code would be able to do anything meaningful with it.

On the other hand, if the code inside the try / catch throws exceptions that you expect, catching and wrapping them in a custom exception is a good idea. For example, if your code reads from some special file private to your component, and the read causes an I/O exception, catching that exception and reporting a custom one is a good idea, because it helps you hide the file operation from the caller.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 6
    he is passing the original exception in as the innerexception to the custom one so this is actually ok – Robert Levy Feb 03 '14 at 15:33
  • @RobertLevy Passing the original exception is not an excuse for throwing a meaningless exception. Please re-read my first paragraph to understand why it is an awfully wrong thing to do. – Sergey Kalinichenko Feb 03 '14 at 15:34
  • @RobertLevy Think about it this way: is `MyCustomException` meaningful when the inner exception says `IndexOutOfRangeException`? – Sergey Kalinichenko Feb 03 '14 at 15:36
  • 3
    @dasblinkenlight don't agree with you - custom exception is more high-level exception than one caught by this catch block. If you are initalizing application, it will be something like `ConfigurationException("Cannot initialize trader module", e)`. High level client (e.g. some service) will deal with configuration errors instead of having fun with low-level `IndexOutOfRangeException` and `FileNotFoundException` (and basic `Exception`) – Sergey Berezovskiy Feb 03 '14 at 15:38
  • @SergeyBerezovskiy You are disagreeing with something I did not say. The situation with `DataAccess` falls squarely within what I describe in the second paragraph of the answer - i.e. hiding exceptions in the implementation, which the answer says is *good*. `IndexOutOfRangeException`, on the other hand, is a programming error. No client is supposed to have fun with it, ever, because it is a bug which cannot be meaningfully be dealt with. – Sergey Kalinichenko Feb 03 '14 at 15:42
  • 1
    @dasblinkenlight but from point of client problem is same - trader module cannot be initialized - it's initialization/configuration error (I would maybe pick `ModuleInitializationException`) - you should investigate logs to find source of problem - is it programming error or missing file. That is investigation part of problem, and that's why original exception is assigned to inner exception. Consider your stomach - when it throws exception - it's just `MyStomachHurtsException`, not something specific :) – Sergey Berezovskiy Feb 03 '14 at 15:46
  • 2
    @SergeyBerezovskiy The fundamental problem with the "wrap everything" approach is that it is not clear who needs to investigate the exception. If I wrap only meaningful exceptions, my clients would still come to me with my `IndexOutOfRangeException`, but they might be able to investigate the `MyCustomException` + `FileNotFound` ones on their own, without bothering me. In situations when there's lots of clients, this is a big time saver for both me and my clients. – Sergey Kalinichenko Feb 03 '14 at 15:55
  • 1
    @dasblinkenlight: I would argue the opposite: while blind exception wrapping should be performed as close to an API layer boundary as possible, a method which calls a supplied delegate in some particular context and wraps any exception thrown thereby will make it possible to distinguish exceptions which occurred within the delegate from those which occurred elsewhere. Since it will have no way of knowing what exceptions the delegate might throw, it will also have no way of knowing which ones are significant. – supercat Feb 05 '14 at 00:39
  • Pretty interesting discussion has developed here, thank you very much everyone. A related question has been posted here trying to resolve this important question for me: http://stackoverflow.com/questions/23340119 - I'd appreciate your input there as well. – matori82 Apr 29 '14 at 10:00
5

It's completely OK. You don't have to catch each exception type separately. You can catch specific type of exception, if you want to handle it in specific way. If you want to handle all exceptions in same way - catch base Exception and handle it as you do. Otherwise you will have duplicated code in each catch block.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • 1
    What about critical system exceptions like OutOfMemoryException? These would be also caught in this catch block and wrapped in custom exception but I am not sure what happens next with the application... it could be forcibly closed by OS causing data corruption etc... – matori82 Apr 28 '14 at 10:58
  • 1
    Any exception is critical to your application. If it will not be handled, application will crash. If this particular exception should not be handled in specific way, then it should be handled as any other exception. E.g. if you were importing contacts, then wrap it by your custom exception `DataImportException` and throw it to caller. From caller point of view, its data import operation failed. No matter what was the reason - data is not imported. – Sergey Berezovskiy Apr 28 '14 at 11:38
4

This is what I usually say about exception handling:

  • The first thing to do with exceptions is ... nothing. There will be a high level catch all handler (like the yellow ASP.NET error page) that will help you, and you will have a full stack frame (note this is not the case in other non .NET environments). And if you have the corresponding PDBs around, you will also have the source code line numbers.
  • Now, if you want to add some information to some exceptions, then of course you can do it, at carefully chosen places (maybe places where real exceptions actually happened and you want to improve your code for future errors), but make sure you really add value to the original one (and make sure you also embark the original one as the inner exception, like you do in your sample).

So, I would say your sample code could be ok. It really depends on the "Custom error message" (and possibly exception custom properties - make sure they are serializable). It has to add value or meaning to help diagnose the problem. For exemple, this looks quite ok to me (could be improved):

string filePath = ... ;
try
{
    CreateTheFile(filePath);
    DoThisToTheFile(filePath);
    DoThatToTheFile(filePath);
    ...
}
catch (Exception e)
{
    throw new FileProcessException("I wasn't able to complete operation XYZ with the file at '" + filePath + "'.", e);
}

This doesn't:

string filePath = ... ;
try
{
    CreateTheFile(filePath);
    DoThisToTheFile(filePath);
    DoThatToTheFile(filePath);
}
catch (Exception e)
{
    throw new Exception("I wasn't able to do what I needed to do.", e);
}
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
  • How about `catch (System.IO.IOException e)` with `throw new MyFileIOException("...")` followed by `catch (Exception e)` with `throw new MyFileException("Something not related to file IO went wrong.")`? In other words, instead of one catch-all custom exception, one or more specific custom exceptions in addition to a catch-all custom exception. Or perhaps, a single catch-all custom exception combined with [Exception.Data](http://stackoverflow.com/questions/144957/using-exception-data). – DavidRR Dec 11 '15 at 14:55
  • @DavidRR - Well, the second "catch all" `catch(Exception)` seems useless, since you will get that information from the highest exception handler anyway – Simon Mourier Dec 11 '15 at 15:06
  • Hmm, not sure I understand your point... I'm suggesting the possibility of more than one `catch` block, and throwing different custom exceptions from each. The last `catch` block would catch `Exception` and throw the most general custom exception (which would wrap `Exception`). With respect to your example, that might be `FileProcessException`. And `FileProcessIOException` if there happened to be value in specifically reporting an IO-related exception. `FileProcessIOException` would be derived from `FileProcessException`. – DavidRR Dec 11 '15 at 15:52
  • @DavidRR - different catch for different exceptions (not Exception) is fine, but the last "catch all" seems useless to me, unless you really add something to it – Simon Mourier Dec 11 '15 at 15:54
  • I think my use of the term "catch all" is confusing. `Exception` will catch anything; I'm not suggesting replicating that. What I'm really suggesting is the possibility of a **custom exception class hierarchy** that conveys a business-specific context. The base class `FileProcessException` would represent all exceptions related to processing a certain file. And a derived class `FileProcessIOException` would represent a more specific error situation. A client could choose to catch either one. – DavidRR Dec 11 '15 at 16:09
3

Foreword: I consider this pattern to be usable only in certain conditions and with full understanding of its good and bad sides.


Statement 1: An exception is when a member fails to complete the task it is supposed to perform as indicated by its name. (Jeffry Richter, CLR via C# Fourth Edition)

Statement 2: Sometimes we want from a library member to a) Get a result or b) Tell us it's impossible and we don't care about all the details, we'll just send details to the library developers.

Conclusion from St.1, St.2: When implementing a library method we can wrap a general Exception and throw a Custom one, including the source one as its InnerException. In this case a developer using this member will need to catch just one exception and we'll still get debug information.


Case 1: You are implementing a library method and don't want to expose it's internals or you intend/assume to change it's internals in future.
public string GetConfig()
{
    try
    {
        var assembly = Assembly.GetExecutingAssembly();
        var resourceName = "MyCompany.MyProduct.MyFile.cfg";

        // ArgumentNullException
        // ArgumentException
        // FileLoadException
        // FileNotFoundException
        // BadImageFormatException
        // NotImplementedException
        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        // ArgumentException
        // ArgumentNullException
        using (StreamReader reader = new StreamReader(stream))
        {
            // OutOfMemoryException
            // IOException
            string result = reader.ReadToEnd();
        }
        return result;

        // TODO: Read config parameter from DB 'Configuration'
    }
    catch (Exception ex)
    {
        throw new ConfigException("Unable to get configuration", ex);
    }
}

It's a pretty solid code and you are sure it won't throw an exception ever. Because it's not supposed to. Are you sure? Or you'd wrap it into try-catch, just in case? Or you'd make a developer do this job? What if he doesn't care whether this method will succeed, may be he has a backup plan? May be he'll wrap call to this method to try-catch(Exception e) instead of you? I don't think so.

Pros:

  1. You are hiding implementation details and are free to change it in future;
  2. The callers don't have to catch whole bunch of different exceptions, if they care, they can look at the InnerException.

Cons:

  1. You are losing stack trace (It may be not that important for a third-party library);


Case 2: You want to add information to exception. It's not directly the code you wrote in the question, but it's still catching a general Exception and I think this is important underestimated part of the Exception Handling facility.
catch (Exception ex)
{
    ex.Data.Add(paramName);
    throw;
}

Addition: I would edit your pattern in the following way:

try
{
    // code that can cause various exceptions...
}
catch (Exception e)  
{
    if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
    {                                       
        throw;
    }

    throw new MyCustomException("Custom error message", e);
}


Summary: This pattern can be used when developing a library public method to hide implementation details and simplify its using by developers.
d_z
  • 688
  • 3
  • 11
  • 2
    ***Case 1***, *Cons: 1. You are losing stack trace (It may be not that important for a third-party library);* Are you? As you indicate, when you wrap an exception in a custom exception, the wrapped exception is available via `CustomException.InnerException`. In other words, doesn't `InnerException` provide the stack trace? – DavidRR Dec 11 '15 at 14:40
1

The general principal with Exceptions is to catch them and handle them locally if applicable and otherwise allow them to bubble up to the top level container.

It all depends on the context that your application is running in. For example if the application is an ASP.Net web application then certain exceptions can be handled by the ASP application server in IIS but expected application specific errors (ones that are defined in your own interfaces) should be caught and presented to the end user if appropriate.

If you are dealing with I/O then there are a lot of factors that are beyond your control (network availability, disk hardware, etc.) so if there is a failure here then it is a good idea to deal with it straight away by catching the exception and presenting the user with and error message.

Most importantly don't fail silently so don't wrap the exceptions in your own exception and then ignore them. Better to allow them to bubble up and find them in the web server log for example.

phn
  • 1,720
  • 1
  • 14
  • 10
1

After reading the question, answers and the comments posted, I think a thorough answer by Iain Galloway could explain much of it in broader way.

My short and sweet point to explain it,

  1. The exceptions should be caught and custom exception should only be thrown when you want to hide the technical details from the end user and want only user to get informed that something failed with some proper message but on the other hand would always log the same exception to the log file so that we can provide some technical assistance and help to the user if the same scenario occurs frequently and from the log file we get the information that we need (technically).
  2. You explicitly catch some exception type and know the exact scenario in what case the exception is thrown by the method and then handle it and have some predefined codes that can explain the error in the other methods calling the function and have some actions to take on that error codes.
    This could rather help if you call many functions and they all throw some pre-defined exception with exception codes which can help categorizing them and take some actions accordingly.

In some other comment you mentioned, what about system critical exceptions like OutOfMemoryException you would only be able to catch those exception if you have explicitly added, [HandleProcessCorruptedStateExceptions] section over the function and to get detail answer in what scenario you should handle it read this SO post

Community
  • 1
  • 1
Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58
1

The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.

The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.

The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:

try { 
something(); 
} 

catch (Exception ex) {}

or this in Python:

try:
something()
except:
pass

Because these can be some of the hardest issues to track down.

A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can

Richa Jain
  • 641
  • 6
  • 19
0

Depends on what you have to do with when exception arises. If you wish to globally handle all the exceptions, that's OK to re-throw the exception to the caller method and let it handle the exceptions. But there are many scenarios where exceptions must be handled locally, in such cases, catching exception with known types should be preferred and a last catch should catch Exception ex (to catch an unexpected exception) and re-throw the exception to caller.

try
{
    // code that can cause various exceptions...
}
catch (ArithmeticException e)
{
    //handle arithmetic exception
}
catch (IntegerOverflowException e)
{
    //handle overflow exception
}
catch (CustomException e)
{
    //handle your custom exception if thrown from try{} on meeting certain conditions.
}
catch (Exception e)
{
    throw new Exception(e); //handle this in the caller method
}
Sarvesh Mishra
  • 2,014
  • 15
  • 30
0

It might be good practice or might not depending on the scenario. Though I am not an expert here, to my knowledge I consider doing this is fine when you are not sure about exception. I see you are considering a code in try that can throw multiple exceptions. If you are not sure about which exception can be thrown, it is always better to do it the way you have done it. Anyway the execution will not allow you to execute multiple catch blocks. Whenever you hit first catch block, control will go to finally or wherever next you want it to go but definitely not another catch block.

LearningAsIGo
  • 1,240
  • 2
  • 11
  • 23
0

First universal rule - Never swallow exceptions !! When you write a piece of code, you should be able to predict most of the cases where there could be an exception, and requires to be notified, such cases should be handled in the code. You should have a general logging module, that logs any exception caught by the application, but might not be of any use to the user actually.

Show the errors that are relevant to the user, for example the user of the system might not understand IndexOutOfRange exception, but it might be an interesting subject for us to research on why this occurred.

We need to always know what went wrong and when so that we could analyze the root cause and prevent it from happening again, because if it could happen once. It will happen again and may be it could cause a disaster. The only way to find what is wrong is by logging in what ever error the application encounters.

0

You can use ellipses too.

   catch (...) 
   {
        // catches all exceptions, not already catches by a catch block before
        // can be used to catch exception of unknown or irrelevant type
   }

Except this what you can do is nested try-catch

try
{
    //some code which is not for database related 
    try
    {
      //database related code with connection open
    }
    catch(//database related exception)
    {
        //statement to terminate
    }
    **finally()
    {
        //close connection,destroy object
    }**
}
catch(//general exception)
{
    //statement to terminate
}

According to me, this would help you to get more concise idea of your error type.

Divyek
  • 155
  • 2
  • 12
0

I think that this issue is very speculative, it often depends on specific case, but I did some research and I will share it. First, I want to express my opinion on code from lain Galloway:

try {
  GetDataFromNetwork("htt[://www.foo.com"); // FormatException?

  GetDataFromNetwork(uriArray[0]); // ArrayIndexOutOfBounds?

  GetDataFromNetwork(null); // ArgumentNull?
}
catch(Exception e)
{
  throw new WeClearlyKnowBetterException(
    "Hey, there's something wrong with your network!", e);
}

If GetDataFromNetwork could throw FormatException, than this external calling should has own method, in which will be handled that exception and it should be converted into custom exception like here:

try {
  GetDataFromNetwork();
} catch (FormatException ex) {
  // here you should wrap exception and add custom message, which will specify occuring problem
}

When I´m creating custom exception for specific application, I extend MyGeneralException from Exception and every more specific exception will extend MyGeneralException. So, at the moment you are wrap into custom exception, you should then put in the method throws MyGeneralException.

I´m using rule, which I took over from more experienced developers than I am, that at the first place, when could be thrown some foreign exception, there it should be wrappped into custom, because you don´t want to be dependent on the other module´s exception.

Then If you will use method anywhere, you will put only MyGeneralException into method signature throws and it will bubble up through the layers of application. It should be catched and processed at the highest level, mostly exception message is used to creating response by some handler, or it could be handled manually.

Mainly during designing exception handling there should be considered, if your library will use third party developers, they are not interest in processing many exceptions.

Peter S.
  • 470
  • 1
  • 7
  • 17