How is one supposed to benchmark methods that throw exceptions using jmh?
I tried the following under jmh 1.19:
#Benchmark
public void throwException() throws IllegalArgumentException
{
throw new IllegalArgumentException("Hard-coded exception");
}
but got this error:
# Run progress: 0.00% complete, ETA 00:02:00
# Fork: 1 of 3
# Warmup Iteration 1: <failure>
java.lang.IllegalArgumentException: Hard-coded exception
[...]
Am I supposed to blackhole exceptions as follows?
#Benchmark
public void throwException(Blackhole bh)
{
try
{
throw new IllegalArgumentException("Hard-coded exception");
}
catch (IllegalArgumentException e)
{
bh.consume(e);
}
}
or is there another way to tell jmh to accept thrown exceptions?
Summarizing the answers I've received from I've received from Kiril S. and Oleg Estekhin:
JMH will always fail if a benchmark method throws an exception. To correct this, the benchmark method must catch the exception. It can then consume the exception using a Blackhole object, or return it from the benchmark method. This will prevent the compiler from optimizing-away the throw statement.
Related
I am trying to catch a concurrent modification exception in Firestore in Datastore mode with Objectify. I created a method and ran it 50 times in 1 second to try and catch the exception. I found that I can only catch the exception if I use a transaction.
Is there a way to catch the CME without a transaction?
This does not catch the exception when ran 50 times in 1 second (even though I can see in the logs the entity is not always updated due to the 1/sec write limit):
try {
Entity entity = ofy().load().type(Entity.class)
.filter("username", "username1")
.first()
.now();
entity.setName("username2")
ofy().save().entity(newEntity).now();
} catch (com.google.cloud.datastore.DatastoreException datastoreException) {
// Never catches anything
} catch (Exception e) {
// Never catches anything
}
This catches the exception when ran 50 times in 1 second:
try {
ofy().transact(new VoidWork() {
public void vrun() {
Entity entity = ofy().load().type(Entity.class)
.filter("username", "username1")
.first()
.now();
entity.setName("username2")
ofy().save().entity(newEntity).now();
}
}
});
} catch (com.google.cloud.datastore.DatastoreException datastoreException) {
// Catches this error: Aborted due to cross-transaction contention. This occurs when multiple transactions attempt to access the same data, requiring Firestore to abort at least one in order to enforce serializability.
} catch (Exception e) {
}
Without a transaction the write is concerned a blind write. A blind write writes the content of the write even if another write has happened between your read & your write.
You should not expect a concurrent modification exception without a transaction.
I am new to the functional style of programming using vavr.
I have a method returns the data when its executed successfully and if it fails, it returns the MyCustomRunTimeException.
In my Service class, I am calling this API method, when API method fails I have to catch the exception and going to clear my application cache and return the same exception to the caller (another service method in my case).
if method call success I have to return the actual object, not the Try wrapped object.
How can I achieve this using vavr Try?
I tried to use different methods in vavr Try.recover but I am unable to throw the same exception.
Any sample example or snippet could be very helpful for me if some can provide.
Thanks in advance.
Example:
Foo doFoo() {
throw new MyCustomRunTimeException();
}
method1(){
try{
doFoo();
}catch(MyCustomRunTimeException ex){
clearcache();
throw ex;
}
}
Basically, if your function throws, you want to do something (in case of failure) then throw it again?
How about this?
Foo doFoo() {
throw new MyCustomRunTimeException();
}
Foo myService() {
return Try.of(() -> doFoo())
.onFailure(e -> clearCache())
.getOrElseThrow(identity());
}
If I may: since you want to try functional style, we usually don't rely on exceptions in FP, instead we rely on types that represent possibility of failure, like Either<MyBusinessProblem, Foo>.
Then your code would look like:
Either<MyBusinessProblem, Foo> doFoo() {
return Left.of(new MyBusinessProblem());
}
Either<MyBusinessProblem, Foo> doFoo() myService() {
return doFoo()
.peekLeft(businessProblem -> clearCache());
}
As a bonus, now your code is explicit and you don't risk forgetting handling an error.
Consider the following code
import 'dart:async';
Future main() async {
try {
print("trying");
await doSomething();
print("success");
} catch (e) {
print("caught");
}
}
Future<int> doSomething() async {
await doSomethingElse();
return 5;
}
Future<int> doSomethingElse() async {
throw new Exception();
}
When run, the exception thrown in doSomethingElse() is caught up in main(), and everything works as expected. But, say the person who wrote the doSomething() method didn't realize that doSomethingElse() was asynchronous, and instead wrote the follow (note the missing await).
Future<int> doSomething() async {
doSomethingElse();
return 5;
}
Now the exception isn't caught at all. Rather, the output now looks like this:
trying
success
Unhandled exception:
Uncaught Error: Exception
Stack Trace:
#0 doSomethingElse.<doSomethingElse_async_body> (file:///C:/code/test.dart:19:7)
#1 Future.Future.<anonymous closure> (dart:async/future.dart:118)
<snip>
What's happening is that doSomething() is returning immediately, and then sometime later, in another context, doSomethingElse() is throwing its error, stopping all execution immediately. I know that an answer to this might be "Well, don't do that then." but I'm considering cases where I might not have control over the methods I'm calling (say if they are part of a library).
This situation leads to a couple of related questions:
As the author of main(), is there any way I can be certain that my call to doSomething() won't end with an unhandled exception? Or am I dependent on the author of doSomething() to make sure all possible exceptions are handled or propagated to the returned Future? Is there a way to attach some sort of global error handler that can catch errors from abandoned Futures?
As the author of doSomething(), if I don't want to wait on doSomethingElse() (say it writes to a log for example, so I neither need the output nor do I need to worry about handling errors). Is there anything I can do to prevent errors in doSomethingElse() from halting the program other than wrapping every call of it a try/catch block (which can be cumbersome an easily overlooked)?
As the author of doSomethingElse(), is there some pattern I can use which allows me to throw Exceptions in a way that callers who wait for the Future to complete can handle that Exception themselves whereas callers that don't wait for the Future don't have to worry about catching the Exception? My best thought in that regard is to return a special object rather than throwing an Exception, but that adds a lot of extra cruft and makes the method much harder use.
Note: I'm using async/await syntax here, but the question should be equally relevant for a more strictly Future based construction (where you return a new Future in doSomething() instead of .then()ing off the one from doSomethingElse()
Uncaught asynchronous errors are handled to the current zone's error handler.
What you are seeing is the root-zone's error handler reporting the error as uncaught, which also terminates the isolate.
What you want is to introduce a different error handler for your code, by running it through runZoned with an error handler:
import "dart:async";
main() {
runZoned(() async {
try {
print("trying");
await doSomething();
print("success");
} catch (e) {
print("caught");
}
}, onError: (e, s) {
print("uncaught");
});
}
Like Greg pointed in its comment you can use Zones to catch unexpected errors from async code.
I have one doubt regarding Try-Catch block.
Below is my code
private void PopulateDDL()
{
try
{
if (my condition)
{
code
}
else
{
throw new Exception(ErrorMessage);
}
}
catch (Exception ex)
{
logerror(ex);
}
}
Which Catch block will be executed if error for below code
else
{
throw new Exception(ErrorMessage);
}
From MSDN:
When an exception is thrown, the common language runtime (CLR) looks
for the catch statement that handles this exception. If the currently
executing method does not contain such a catch block, the CLR looks at
the method that called the current method, and so on up the call
stack. If no catch block is found, then the CLR displays an unhandled
exception message to the user and stops execution of the program.
The catch block you have defined:
catch (Exception ex)
{
RaiseWebError(ex);
}
will be executed first for the exception throw new Exception(ErrorMessage);
If RaiseWebError re-throws the exception this will then be handled by the next try-catch block found futher up the call stack (i.e. the parent method you refer to). But if RaiseWebError handles the exception in some way (perhaps by logging the exception) execution will continue after the first try-catch.
I'm experiencing problems with an exception not caught in my workflows.
I have a custom AsyncCodeActivity surrounded by a TryCatch; anyway, the exception is not caught and, worse, my IIS pool hosting the workflow is sometimes restarted.
Looking at this question/answer (Exception escapes from workflow despite TryCatch activity), I'm thinking that the problem is in the way I rethrow exceptions. This is how I usually write async code activities:
protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
{
Action<object> execute = s => this.Execute();
var task = new Task(execute, state, CancellationToken.None, TaskCreationOptions.PreferFairness);
task.ContinueWith(s => callback(s));
task.Start();
return task;
}
protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
{
var task = result as Task;
Contract.Assert(task != null);
if (task.IsFaulted && task.Exception != null)
{
Contract.Assert(
task.Exception.InnerException != null,
"It is expected that the inner exception in a task is not null");
const string Message = "An exception was thrown while doing something";
Logger.ErrorException(Message, task.Exception.InnerException);
throw new WorkflowApplicationException(Message, task.Exception.InnerException);
}
}
private void Execute()
{
// Do something here
}
Is it the correct way to handle exceptions in async code activities? if yes, how should I prevent my workflow from aborting (and sometimes restarting IIS)?
Thanks
I don't think WorkflowApplicationException was meant to be thrown by your code. I wouldn't be surprised if somewhere we are treating this exception differently and not invoking the TryCatch block because this exception (and it's subclasses) are typically thrown by the workflow runtime and there wouldn't be a point of catching them in an activity if the runtime is hosed.
You could try throwing a different exception to see if that makes a difference.