c# Throw new Exception with in Loop OK? - c#-4.0

I've a list of records retrieved through external web service. Some of the data are rubbish and would like to log the record that failed by throwing a new exception.
Wondering if this is best way to handle, as i read exception can impact the performance?
Pseudo code e.g.
try
Loop through listOfRecords
perform logic.
catch
throw new exception (record details)

It depends on what you want to do with the rest of the records when an exception is encountered. Your current implementation would terminate the loop on the first error.
If, however, you simply want to mark the record in some way as "unprocessed" or "errored" and continue with the remaining records, you'd want to handle the error entirely within the loop:
foreach (var record in records)
{
try
{
Process(record);
}
catch (TypedException ex)
{
LogError(ex);
MarkAsUnprocessed(record, ex);
// respond in some other way as well?
}
}
Ultimately, the exception handling logic belongs wherever it logically makes sense to handle the exceptions. Catching exceptions is the easy part, that's a simple construct of the language being used. Meaningfully handling exceptions is another story entirely, and is a logical construct independent of the language being used.
Edit: It's also very much worth noting that your pseudo-code implies this way of handling exceptions:
try
{
// something
}
catch
{
throw new Exception("something");
}
This is very bad practice. Throwing an entirely new exception essentially tosses out the exception that was caught, which gets rid of some very useful debugging information (not the least of which being the stack trace). If you want to immediately log the exception and then let it continue up the stack, simply use the keyword throw by itself:
try
{
// something
}
catch (Exception ex)
{
// log the exception
throw;
}
If you want to add context to the exception, you can modify its properties before throwing it again. Or perhaps even better, throw a custom exception (not Exception) and attach the existing one as the InnerException property:
try
{
// something
}
catch (Exception ex)
{
throw new RecordProcessingException("some additional context", ex);
}
If, on the other hand, there's nothing meaningful to be done with the exception in the current context, don't even catch it at all. Let it bubble up the stack until it encounters code that can meaningfully handle it.

It's not the best way, since you only need the log-writing functionality. Just write to the log and continue the loop.

Related

Does PerformImmediateLogin throw a custom exception? If so, what is the type?

When calling we'd like to be able to catch any exceptions in a try catch and hand over to our handler.
IVaultClient vaultClient = new VaultClient(vaultClientSettings);
try {
vaultClient.V1.Auth.PerformImmediateLogin();
} catch ( Exception e) {
}
Yes, in general, all VaultSharp APIs tend to throw this custom exception.
VaultApiException
See here for the fields.
https://github.com/rajanadar/VaultSharp/blob/master/src/VaultSharp/Core/VaultApiException.cs
However, the PerformImmediateLogin can also throw the Exception type when the HTTP login call to Vault does succeed but the response has an empty AuthInfo object (thus not giving back a vault token). This may or may not happen in real life, but this is the only case where Exception is thrown. Otherwise, you can always expect VaultSharp to throw the VaultApiException type.

How can I manually mark an invocation as Failure in an Azure Function?

I have tried many things but the only way I can force AzFn to understand the invocation has failed, is to throw an exception and not handle it. So, if I return an HttpResponseException, AzFn will consider the invocation as a success. That feels wrong.
catch (Exception ex)
{
logger.Error($"{nameof(ex)}: {ex.Message}", ex);
response = req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message, ex);
}
This should produce an invocation marked as fail but it doesn't.
Any exception thrown from your function will mark the function as failed. In your code above you're swallowing the exception, so we consider it successful. If you instead rethrow the exception, the function will be marked as failed. We'll automatically return a 500 in such cases on your behalf.
We don't look at the HttpStatusCode you return to determine if the function is successful, only whether the function ran successfully to completion w/o exception. If your function is able to return a response, it is successful from our point of view.

Checked exceptions in visitors

I am learning ANTLR4 and I have no previous experience with parser generators.
When I define my own visitor implementation, I have to override methods of the BaseVisitor (I am looking for instance at the EvalVisitor class at page 40 of the book). In case my method implementation possibly throws an exception, what should I do? I cannot use a checked exception since the original method has an empty throws clause. Am I expected to use unchecked exceptions? (this seems a bad Java design). For instance, assume that in the EvalVisitor class I want method visitId (page 41) to throw a user-defined exception, say UndefinedId, rather than returning 0. How should I write my code?
You have two options:
Handle the exception inside the visitor method itself.
Wrap your checked exception in an unchecked exception. One possibility is ParseCancellationException, but you'll have to determine for yourself whether or not that makes sense in your application.
try {
...
} catch (IOException ex) {
throw new ParseCancellationException(ex);
}

Catch the Exception Running on different thread/callback

I have a Function executing Some piece of code Like,
Protected void XXXXfunc()
{
//i register a callback for asynchronous operation below is just an example
// not true to its operation
byte[] buffer = new byte[10];
s.BeginReceive(buffer, 0, 10, SocketFlags.None,
new AsyncCallback(OnMessageReceived), buffer);
}
// Callback function
XXXX callback OnMessageReceived(XXXX)
{
//Something Goes wrong here i throw an exception
throw(exception);
}
Where and how do i catch this exception or where is this exception funneled to be caught.
In the callback, the only place you can catch it.
And yes, that's a very awkward place because that callback runs on a thread you didn't start and runs completely asynchronously from the rest of your code. You have to somehow let the main logic in your program know that something went wrong and that corrective action needs to be taken. Which typically requires raising an event that gets marshaled back to your main thread. At the very least to let the user know that "it didn't work".
This kind of problem is the prime motivation behind the Task<> class in C# version 4 and the async/await keywords added to C# version 5. Which doesn't actually do anything to help the user deal with random failure, it just makes it easier to report.

How to let program to run instead of an exception in c#?

I am writing a program to read all files from an array.
Suppose in between if any file is corrupt or any reason it will stop the execution in between and throw an exception
I want to let the code running till end and at last it logged the error files instead of throwing exception?
try{
doSomethingThatMayRaiseAndException();
}
catch (Exception e){
NotifyTheUserThatSomethingBadJustHappened();
}
Exception here is the base class for exceptions, you may need to use a more specific one if you want to provide the user with details. But right now, what you need to learn is how to deal with exceptions. You can use the link provided by Oded, it is a good start. Then note what is the raised exception you need to handle, and handle it.

Resources