when it is correct purpose of exceptions - oop

I am studying OOP, and I did not understood the concept of exception.
What are the correct uses of exceptions?
Why use exceptions when you already know a possible exception?
For example, I have seen a code sample where the programmer needed to access a file, and had an exception in case the file does not exist. Something like "catch(fileDoesNotExist e)".
Why not use an if to verify before take the action? And use exception only for not known issues, for logging or error messages.

The idea behind the concept of exception was to decouple the error handling code from the "normal" behaviour flow control. That lets to manage/handle the exception further up the call stack.
Historically, with structured language, error handling code (file opening error,...) was mixed within the "business" application code. It was also painful to improve the code in order to manage new error codes.
What are the correct uses of exceptions?
If it is not normal that your file doesn't exist or cannot be opened => it is considered as an exceptional situation => exception => exception handler
Why use exceptions when you already know a possible exception?
To decouple the business application code from the error handling. That eases source code readibility and maintenance.

Exception:
Exception is that interrupt(break) the normal flow of the program.It's thrown at runtime.
Exception Handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc
In java there are mainly two types of exception that checked and unchecked.Other than Error is there
Hierarchy of Exception classes in Java
Why use exceptions when you already know a possible exception?
basically exception handling use to mainly,we assuming in that our particular code will occur some(NullPointerException,ArrayIndexOutOfBoundsException etc..)exception.If we not Handle that,program will break.Actually that Exception it may or may not will happen.But so we need to handle normal flow of the program it occurred or not.Otherwise after that particular code section not executing.

Related

Why in mulesoft "on Error Propagate" rethrows the same error?

I am new to mulesoft and while studing it i strugle to understand why on module "onErrorPropagate" the error is being rethrown after executing the scope.
can you explain the benefits?
An on-error-propagate will rollback any transactions, execute, and use that result to rethrow the existing error––meaning its owner will be considered as “failing.”
The best use is in a layered system, to allow each layer to do its own small part of an error response.
If you are familiar with Java you can think of it as catching the exception and re-throwing it. For example, sometimes you want to do something with the error yourself, but still want to propagate it upwards for higher levels to deal with.
You could add logging in a specific flow for the error but then leave it to the parent flows to actually deal with the exception.
The "onErrorPropagate" propagates (rethrows) the error to the parent flow (or the global error handler if it's already reached the main flow).
This can be usefull in a few cases.
Say you have some flow specific error handling (e.g. if something goes wrong, set a default payload).
Then you propagate this error to the next level where you have your Global error handler that, say, stores some info in a QA database.
You don't want to have that database connector in every single error handler.
In this way you can achieve a 'java inherritance' like structure, for your errors.
Side note: if you want your error to only be handled and do nothing further, you can use "onErrorContinue"

How can I display exception messages from custom functoid errors in the BizTalk Administration Console?

My goal is to influence the error descriptions that appear in BizTalk Administration Console in the Error Information tab of suspended instance windows, after errors occur in my custom functoids. If possible, I would also like the ErrorReport.Description promoted property to display this error description on the failed message.
I've read everything I can find about custom functoid development, but I can't find much about error handling within them. In particular, whenever my functoids throw exceptions, I see the boilerplate "Exception has been thrown at the target of an invocation" message that occurs whenever exceptions occur through reflection, rather than the message on the exception itself.
I had hoped to find something within the BaseFunctoid class framework that would allow me to submit an error string, so as to traverse the reflection boundary. Is there some way to pass error information from within a custom functoid, such that the BizTalk Administration Console will display it?
If I emulate the approach taken by DatabaseLookupFunctoid and DatabaseErrorExtractFunctoid, is there some way I can fail the map with the extracted error, rather than mapping it to a field on the destination schema as is shown in its examples?
The simplest way to do this is using custom C#, writing something like this in your code:
System.Diagnostics.EventLog.WriteEntry("EVENT_LOG_SOURCE", "Error message...", System.Diagnostics.EventLogEntryType.Error);
As Johns-305 mentions, you need to make sure your event source is registered (e.g. System.Diagnostics.EventLog.CreateEventSource("EVENT_LOG_SOURCE", "Application") - but this should really be done as part of your installation steps with an EventLogInstaller or some kind of script to set up the environment). It's certainly true that error handling in BizTalk is just .NET error handling, but one thing to keep in mind is that maps are actually executing as XSLT, and the context in which their executing can have a major impact on how exceptions and errors will be handled, particularly unhandled exceptions.
Orchestrations
If you're executing a transform in an orchestration that has exception handling in it, the exception thrown will be handled and may even fall into additional logging you have in the orchestration - in other words, executing a throw from a C# functiod will work the way you'd think it would work elsewhere in C#. However, I try to avoid this since you never know if a map will at some point be used else where and because exception handling in XSLT doesn't always work the way you'd think (see below).
Send/Receive Ports
Unfortunately, if you're executing a map on a send or receive port and throw an exception within it, you will almost definitely get very unhelpful error message in the event log and a suspended instance in the group hub. There is no easy, straightforward way to simple "cancel" a transform - XSLT 1.0 doesn't have any specified way of doing that (see for example Throwing an exception from XSLT). That leaves you with outputting an error string to a particular node in the output (and/or to the EventLog), or writing lots of completely custom XSLT to try to validate input, or designing your schemas properly and using a validating component where necessary. For example, if you have a node that must match a particular regex, or should never be empty, or should never repeat more than X times, make sure you set those restrictions on the schema and then make sure you pass it through the XmlValidator or similar before attempting to map.
The simplest answer is, you just do.
Keep in mind, there is nothing special at all about error handling in BizTalk apps, it's just regular plain old .Net error handling.
So, what you do is catch the error in you code, write the details to the Windows Event Log (be sure to create a custom Event Source) and...that's it. That is all I do. I don't worry about what appear in BT Admin specifically.strong text

Handling pgPL/SQL exceptions From QtSQL

Short and simple:
How to catch pgPL/SQL exceptions with QtSQL?
I haven't found any example or info at the docs.
More details:
I'm developing the front end for a system with Qt 5.3. The database perform some validation at some of the inputs and raise custom exceptions when something is invalid. What I want is to be able to handle these exceptions at he front end code, showing appropriate messages to the user.
EDIT:
I have tried to use the QSqlError class. Although it gave me the exception, it gave me too much data which will need to be parsed to be useful. Is there a way to get the exception raised without parsing the messages?

Dealing with exceptions in VB.NET in terms of Exception.Message

I am writing a program that retrieves data from an industrial device and exports it to a MySQL database. For interacting with the device, I am using a DLL driver provided by the manufacturer. In this DLL, there is a custom-made exception which is thrown when there is a communication error or any other type of abnormal situation when communicating with the device.
The problem is that there is a single class exception. So, when I catch an exception of that type, I cannot really tell which particular problem happened since there are several ones (connection timeout, trying to access an invalid memory address, etc.).
So what I am doing for the moment is to use the Exception.Message property. So for example if the exception message contains "Invalid Address" then I know that the error is due to trying to access an illegal address within the device, similarly if the exception message contains "connection timeout" I know that there was an exception timeout. But this approach looks really dangerous since the messages may change in future releases of the DLL.
What can I do to deal with this problem in a better way?
If you're lucky the "generic" Exception has an InnerException with the real exception type.
If all of the exceptions have the same type and the only difference are the messages, then your solution is the best. Just hope the manufacturer does not change anything and make sure to test every new version...

NHibernate Error reporting advice

This is not so much a problem as advice on best practice really. I am writing an ASP.Net MVC application, and in my DAL i am using NHibernate, but what do you do if an exception is thrown in your DAL?
Do you catch the exception in the DAL, log the error and then re-throw the exception?
Do you not even attempt to catch exeptions at all and use the Application_Error() method in the global.asax as a generic catch all?
Do you catch the exception log it and return a bool to the controller indicating a success or failure, or do you do something completly different?
Leading on from this how then do you handle informing the users? Do you show a generic "Error Occured - please try again" type page or do you show a more informative error?
This is exactly one of those 'it depends' questions. This is what I do:
Handle all exceptions in Application_Error (or similar sink-like location)
If the exception is base for business logic - say cannot have duplicates, just catch it and act upon it.
If it is an infrastructure exception and there is a good chance you can fix it by retrying - handle it in DAL.
Propagating specific exception info to user has hardly any benefit because usually the user cannot do anything about it anyway. So a generic error message usually makes do.
All unexpected and selected expected exceptions need to be logged with as much info as possible. It is also advisable that you get email with the exception info.
Now specifically to NHibernate - if NH throws an exception it is advised that you close and discard the currently active ISession and just fail. Because the session might be in an unknown/inconsistent state and trying to resurrect it can do more harm than good.
Obviously depending on scale and type of your app and number of various systems/programmers/etc. involved you really might to handle the logging yourself.