Похожие чаты

#ASK We are using spring boot @controllerAdvice to handle the exception

in the project.
The layers in our project are like this >
controller --->facade(to validate the request) ---->service layer(for business logic and interact with database).
Now my question is, should we throw the exception every time and handle it in @ControllerAdvice?
But my senior argued that we should not throw the exception each time because the more level it has to cross to be handled the more cpu cycles it takes.Like if we throw and exception in SERVICE layer it has to pass through facade layer then controller and then it reaches @Controller advice so takes more cpu.
Can anyone please help me to clear this doubt.?

12 ответов

12 просмотров

Don't think this happens. It is not computing anything so not CPU intensive

So what about this link https://cwe.mitre.org/data/definitions/395.html It said if we can we must return something instead of throwing exception

Mohammad
So what about this link https://cwe.mitre.org/data...

If you check my answer carefully, I deliberately asked follow up - what "every time" means exactly? This CWE is a great suggestion, but it demonstrates exactly the opposite of what I said: > means "every time when error condition occurrs and we need to stop normal execution flow" Using exception this way like in CWE - is definitely a bad idea. And it's not because of reduced performance. Yes, performance will be somewhat reduced, but that's not the main reason. Something being null should be checked this way if (something == null) { and not this way try { something.action(); } catch (NullPointerException err) { // "something" is null, deal with it here } And ideally, it should not even be checked for null at all. Something being dereferenced should be assumed never be null, and your code better never have those "... if it's null then ..." kind of places. It will make it much more clean. So it's all about readability and clean code, not about performance. Though performance indeed will somewhat degrade if you'll use exceptions catching everywhere instead of simple null checks. Again, if performance matters that much that degradation due to exceptions handling is noticeable - you already made a mistake by using wrong technology for the job.

Mohammad
So what about this link https://cwe.mitre.org/data...

NullPointerException and ClassCastException never have to be catch.

Dmytro Buryak
If you check my answer carefully, I deliberately a...

Yep at first i misunderstood that u mean using exception and its pressure on cpu doesn't matter at all because it is tiny...thanksssssssssss

Mihai
NullPointerException and ClassCastException never ...

Ok i think i am misunderstanding again😂

What about it exactly you want to know? Why - just google something like "why exception are expensive" or something like that. How much exactly it costs - just measure it. But in any case, this "expensiveness" of exceptions should never be a factor. If you ever considering it, then you're most probably doing something wrong. If you're worried specifically about NPE or other similar exceptions (ClassCast, Arithmetic) - that CWE you linked explains it very nicely. Don't catch such exceptions *to check data*. Just check the data directly instead. In other words "try - catch" should not be used for *flow control*. For flow control you should use "if else". Exceptions compared to control flow statements, have two major powers - they can delegate error processing to callers arbitrary number of levels up the call chain, and also they require callers to deal with exception. Here's a simple example to demonstrate first power: repository.find...() => not found, I don't know how to handle it, just trhow service1.find...() => don't know how to handle, just throw up service2.find..() => don't know how to handle, just throw up controller => I know how to handle it, I'll render 404 json into http request If it's not obvious, here's the same exactly service2, but now called from grpc controller: repository.find...() => not found, I don't know how to handle it, just trhow service1.find...() => don't know how to handle, just throw up service2.find..() => don't know how to handle, just throw up controller => I know how to handle it, I'll render 404 protobuf error object into grpc request As you see, repository, service1 and service2 don't know how to handle "not found" situation, it's not their responsibility, and they have ZERO code to handle it. That's the main difference from C-style error codes - you don't need to write anything in layers that are not responsible for handling that kind of error. Second power, is that exceptions mechanism *requires* dealing with exceptions. Here's C-style code with error codes that forgets to deal with error codition. Yep, it's everywhere is a subject for human mistake if you decide to not use exceptions. res_t res1 = func1(arg1, arg2); if (res1.err) { // deal with error } handleData(res1.data); res_t res2 = func2(arg1, arg2); handleData(res2.data); In contrast, in java, if you're using exceptions, here in this code: var res1 = func1(arg1, arg2); handleData(res1); var res2 = func2(arg1, arg2); handleData(res2); You don't have any checks on result objects, and it's *guaranteed by compiler and java language spec itself* that if func1 throws exception, then code below it will never be called. It's not a subject for human mistake, that's the main difference, and what this "power" of exceptions is about. If you still think that it's worth to sacrifice these two huge code clarity and simplicity benefits for some improved performance (it's improved only for cases when error happens, by the way, not for "happy case", happy path doesn't suffer from increased performance cost), that it's important for your users that they see that 404 page 5ms faster, then you have already made a mistake by using java.

Dmytro Buryak
What about it exactly you want to know? Why - just...

Hi...excuse me for being late❤️...and about your answer ,first u said i must not use "if else" for flow controll but at the end u said exception is kinda java power for simplicity...so i assume u are saing if i am using java i can use exception even for flow controll...am i understand your answer right?if i am not then please tell me...thanksssssssssss

Mohammad
Hi...excuse me for being late❤️...and about your a...

No, you completely misunderstood it. Let me explain once again. ——————— > first u said i must not use "if else" for flow controll I highly doubt that I said that. If I did, then I made a mistake. Or you misinterpreted it somehow wrong. Anyway, that's very wrong. "if else" is the language construct with the sole purpose to be used exactly for flow control. ————————— > so i assume u are saing if i am using java i can use exception even for flow controll NO. I need to work on my statements ambiguity)) Never use exceptions for flow control. Technically you can do it, but don't)) Exceptions (and the name "exception" itself screams for it) are intended to be used for breaking the normal flow, when something (1) unexpected (exceptional) happened and you can't continue normal flow. Also when you (2) don't know where and what measures need to be taken to handle this unexpected situation. (1) is semantic mostly. You can also have a logic for something unexpected in "else" block, that's totally fine. But if-else can be used for any kind of flow control. Exceptions - only for unexpected situations. That (2) part is very important, that's the main technical difference between exceptions and "if else". If there was no that part (2) needed, you could use "if else" easily to meet your needs. Check this code: Person tryParsePerson(String personJsonStr) { try { json = parseJson(personJsonStr); } catch (JsonException e) { return null; } if (!isNameValid(json)) { return null; } if (!isAgeValid(json)) { return null; } return Person.fromJson(json); } The contract of this method, the way how it's designed, is to never throw any exceptions. And it reacts to invalid data by returning no result (null). But not failing anyhow. Here "if else" is used because there is no (2) involved. In this design we know exactly what to do with bad/unexpected situation - return no result. That's by the contract of this method, that's how we designed it. Such design may be fine for tiny isolated applications. But it bumps into 2 huge problems when you try to use it in libraries or applications with more than just couple of classes. - Optional.empty() doesn't carry any information about type of failure; so in calling code you can't understand whether json is invalid or there was no "name" filed in json data. The more your application grows, the more layers/call depth you have, and more important becomes to pass failure information (at least type of failure) up across SEVERAL layers, not just to calling method, but for example 5 methods up the call chain. - calling code will have more and more "if (result.isEmpty()) " kind of checks everywhere (error flag checks); those may seem fine in one or two places, but it will be everywhere eventually, it will be hard to understand code polluted with such error checks, the main normal flow will "drown" among those checks

Dmytro Buryak
No, you completely misunderstood it. Let me explai...

Ok now i understand you...and thankssssssssss for answering ❤️...so usually i must use if and else for flow controll but if my code is getting too big with several layers that cant use same "return" structure then its better to use exception

Похожие вопросы

Обсуждают сегодня

Господа, а что сейчас вообще с рынком труда на делфи происходит? Какова ситуация?
Rꙮman Yankꙮvsky
29
А вообще, что может смущать в самой Julia - бы сказал, что нет единого стандартного подхода по многим моментам, поэтому многое выглядит как "хаки" и произвол. Короче говоря, с...
Viktor G.
2
@Benzenoid can you tell me the easiest, and safest way to bu.y HEX now?
Živa Žena
20
This is a question from my wife who make a fortune with memes 😂😂 About the Migration and Tokens: 1. How will the old tokens be migrated to the new $LGCYX network? What is th...
🍿 °anton°
2
30500 за редактор? )
Владимир
47
а через ESC-код ?
Alexey Kulakov
29
What is the Dex situation? Agora team started with the Pnetwork for their dex which helped them both with integration. It’s completed but as you can see from the Pnetwork ann...
Ben
1
Гайс, вопрос для разносторонее развитых: читаю стрим с юарта, нада выделять с него фреймы с определенной структурой, если ли чо готовое, или долбаться с ринг буффером? нада у...
Vitaly
9
Anyone knows where there are some instructions or discort about failed bridge transactions ?
Jochem
21
@lozuk how do I get my phex copies of my ehex from a atomic wallet, to move to my rabby?
Justfrontin 👀
11
Карта сайта