B
B
beduin012016-09-13 10:57:11
C++ / C#
beduin01, 2016-09-13 10:57:11

Where is the best place to throw exceptions?

I can not understand in any way where it is better to throw exceptions.
The program reads Config.ini at startup. If it is not found, then there is no point in continuing.
I can't figure out how to properly handle this scenario. In the ReadConfig class, if the file is not found, we throw an exception.
try
{
try to read
if it didn't work, then
throw an exception throw new Exception
}
catch()
{
with this code, we will catch the exception in this block
}
Then it turns out that the try-catch block does not make sense here and it is necessary in main where I create an instance of the Config reader wrap everything and put return in the catch block to stop the application.
Or what is the best way to do that?
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Daniil Danilov, 2016-09-13
@kempendyi

In fact, you can catch the exception and generate some error code,
and return it one level up, and then analyze it in the calling code and conclude that your file was not found.
Answering the question, here I would not leave it, because this is the expected user case of your application, namely the config was not found.

A
Anatoliy Mikhailov, 2016-09-13
@yamaoto

If this happens inside the constructor, then the error needs to be issued only through throw.
But if your ReadConfig class reads the config from a call to its method, then you can return null there if something went wrong. This option is convenient so as not to clog the code at the call points.
But if, for example, the file was considered, but there are errors in the config format or in the values, then through throw you can send explanations for the error and display them to the user or to the logs.

M
MrDywar Pichugin, 2016-09-14
@Dywar

Rules for designing exceptions
Show the error window as in normal programs.
The class that should return the config may or may not throw an exception using the TryXXX () approach.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question