I have an exception I can't handle properly in Xamarin.Forms due to a missing member in the WebExceptionStatus enumeration, namely the NameResolutionFailure member.
Does anyone know how I can properly handle the exception in this specific case?
When looking at a previous version of the WebExceptionStatus enumeration, the NameResolutionFailure member is not supported in a PCL.
What you can do to handle this issue is as follows:
case (System.Net.WebExceptionStatus)1:
// your code
Or:
catch (System.Net.WebException ex)
{
if ((int)ex.Status == 1)
// your code
)
I tested this by simply throwing a new WebException like this:
throw new System.Net.WebException("Test", (System.Net.WebExceptionStatus)1);
Which, as I thought, returned an exception with NameResolutionFailure being the StatusCode.
Related
Suppose I have a supplier and some exception occurs while invoking get method of that supplier.
Supplier<> supplier = () -> getSomething();
ResilienceDecorator.executeSupplier( //Edit 1 - Could be ResilienceDecorator.executeCallable
supplier,
resilienceConfiguration,
throwable -> {
log.error("Exception occured", throwable);
return null;
});
Edit 1 - Also same for ResilienceDecorator.executeCallable.
I need a consistent API to know what went wrong during execution i.e. What was the checked exception (Edit 1 - or Unchecked exception) causing the failure so I can
handle business logic. The throwable is not root cause of exception or whatever the supplier had thrown.
If we do not provide a throwable function like above then
every exception is wrapped in a ResilienceRuntimeException and we need a chain of getCause().getCause() to know what went wrong. This is internal to sdk which might change. Again a consistent API is needed.
Is there any alternative & consistent way to know what exception the supplier is throwing? I might need to bubble it up or write a user friendly message based on the exception occured, depending upon buisness logic.
Edit 1-
An example of my current situation.
Supplier<MatDocItm> supplier = () -> {
ErpHttpDestination erpHttpDestination = DestinationAccessor.getDestination(S4_SYSTEM).asHttp().decorate(DefaultErpHttpDestination::new);
return new CustomCommand(erpHttpDestination, params).execute();
}
try {
MatDocItm = ResilienceDecorator.executeSupplier(
supplier,
configuration
);
} catch (ResilienceRuntimeException e) {
throw new ReadException("Failed to read from SAP S/4HANA", e);
}
The supplier can throw runtime exceptions and based on these exceptions I want to give a User friendly error message with proper description.
The supplier can throw a DestinationAccessException (which is runtime exception) if a destination cannot be accessed, is not configured correctly, or does not fulfill certain prerequisites.
Not only the exceptions occured in supplier, I have TimeLimiterConfiguration & if timeout occurs then a TimeoutException can be thrown.
For above MatDocItm example the ResilienceRuntimeException.getCause() will give com.sap.cloud.sdk.cloudplatform.thread.exception.ThreadContextExecutionException. ResilienceRuntimeException.getCause().getCause() will reveal exception that actually caused the error i.e DestinationAccessException. Now ThreadContextExecutionException is internal to sdk and can change if sdk implementation changes. Will this implementation detail remain frozen and never change in future or is there any alternative way to get the root cause?
I would recommend ExceptionUtils.throwableOfType for matching exception type and sub classes.
Alternatively ExceptionUtils.throwableOfThrowable for matching exact type only.
The utility class already provided by dependency org.apache.commons:commons-lang3:3.10
Example:
#Nullable
YourException cause = ExceptionUtils.throwableOfType(throwable, YourException.class);
You can handle the nullable result in an If statement.
As a fan of fluent APIs, I would rather go with java.util.Optional or io.vavr.control.Option.
I want to know why my program is behaving this way.
I have a method that throws an ArithmeticException when trying to divide by zero. I put this method in a try block. When it throws an exception, if at all, the proceeding catch block will catch this ArithmeticException.
I understand this part 100%.
But I did a bit of experimenting. In my method body:
public static int quotient(int number1, int number2) {
if (number2 == 0)
throw new ArithmeticException("Divisor cannot be zero!");
return number1 / number2;
}
I removed the third line. When I removed the third line, the program still ran fine and performed exactly as it did before. It still caught the ArithmeticException error when it occurred.
Is it because ArithmeticException is an unchecked exception and this error is caught only during runtime, thus negating the need for me to specifically declare that this program will cause an unchecked exception? If it was a checked exception, would I specifically need to declare that this method will throw an unchecked exception?
As you stated Arithmetic exception is a runtime exception, you do not need to specify that it throws an exception.
Although you do need to specify if your program throws a compile time exception using a throws statement. One example where you need to check the exception would be an IOException.
I have c#.net code which calls a method from another external/referenced .net assembly. This method I am calling throws an exception if a certain property from the object I am passing it is null. Here it is in a nutshell:
public void Add(string key, object obj)
{
..
//if the Foo property from obj is null then
throw new Exception("Foo property is null or empty")
..
}
In my client code which calls the DLL's Add method, I would like to be able to detect that this particular exception was raised, maybe distinguished by its "Foo property is null or empty" message. Currently, I get a NullReferenceException when it hits this method, so I catch this exception.
Question1:
Can I get the error message associated with the exception being thrown by the code I am calling (in the referenced assembly)??
Question2:
Is this considered bad practice or maybe just atypical?
Obviously, I can disassemble the third-party DLL to discover that my obj I'm passing in must have this "Foo" property set. So, my question here is somewhat for the sake of exercise (and because I'm a n00b).
Catching System.Exception and showing the exceptions Message property is all I needed. At first, I kept getting a NullReferenceException with "Object reference not set to instant of an object" message at the Add method, but I was expecting to get an Exception with the message "Foo property is null or empty" error. Some condition changed in my code and I now get what I expect.
This is the Exception message thrown by Gen_server when its not started.
(ankit#127.0.0.1)32> R11 = system_warning:self_test("SysWarn").
** exception exit: {noproc,
{gen_server,call,
[system_warning_sup,
{start_child,
{system_warning_SysWarn,
{system_warning,start_link,[{system_warning_SysWarn}]},
permanent,10,worker,
[system_warning]}},
infinity]}}
in function gen_server:call/3
in call from system_warning_sup:'-start_child/1-lc$^0/1-0-'/1
in call from system_warning:self_test/1
(ankit#127.0.0.1)33> R11.
* 1: variable 'R11' is unbound
Now, What I want to do is to catch this exception message & put into variable R11 (showed above as unbound). I want to do so because if gen_sever is not started then I want to start after getting this message. I also tried using handle_info but not able to trap the exception or may be not able to implement it correctly. Can any body please help me with this problem providing some code for example.
Both the answers from #W55tKQbuRu28Q4xv and #Zed are correct but a little terse. :-)
There are two ways to locally catch an error: catchand try. Both will also catch non-local returns generated by throw.
catch is the older and simpler of the two and has the syntax catch Expr. If an error occurs in the expression being evaluated then catch returns {'EXIT',ErrorValue}, otherwise it just returns the value of the expression. One problem with it is that there is no way to see how the error return value has been generated so it can easily be faked in the expression. In the same way you can't see if the return value comes from a throw. N.B. this is not a bug but a feature. Also it is a prefix operator with a low priority so you would normally use it like:
R11 = (catch system_warning:self_test (....))
to avoid confusion. This was a mistake, it should have been catch ... end.
throw is more complex and allows you much greater control over over what to catch and how to handle both the normal returns and error/non-local returns. See the manual for a full description. #Zed's example shows the simplest case which catches everything.
> try
> R11 = system_warning:self_test("SysWarn")
> catch
> Ex:Type -> {Ex,Type,erlang:get_stacktrace()}
> end.
Try to use 'catch':
R11 = catch system_warning:self_test (....)
I'm trying to do:
try{
int * i = NULL;
*i = 3;
}catch(Exception &Err){
ShowMessage(Err.Message);
}
I though that this should catch access violation exception and handle it by displaying an error message.
But for some reason I get simple
Access Violation
message instead of full one
Access Violation XXX in module YYY. Writing at address ZZZ.
BTW, ExceptObject() routine returns NULL for some strange reason.
What am I missing here?
In BCB5, catching an EAccessViolation works, e.g.:
#define AV_TRY { try {
#define AV_CATCH } catch(EAccessViolation &av) {Application->MessageBox((("Access Violation caught: " + string(__FILE__) + "; " + string(__FUNC__) + "; " + IntToString(__LINE__) + "\n\n") + av.Message.c_str()).c_str(), ("Program Error in " + string(class_name.c_str())).c_str(), MB_OK);} }
Note that class_name is specific to this project and should probably be replaced by AnsiString(this->ClassName) or left out. Also I've switched this code from logging silently to a database, to showing a MessageBox. I just wrap code where I've observed AVs in an AV_TRY ... AV_CATCH.
See the MSDN blog entry on Mixing SEH and C++ Exceptions. These are two different types of exceptions. Trying to catch a structured exception, generated by the OS, as a C++ exception isn't the correct way out of the box.
Temper this bit with this posting on not doing that.
Catching access violations can be a nice goal -- but something you may want to do within the context of debugging only. Catching access violations (or other major exceptions) in production code and trying to handle them is seldom going to result in correct operation.
Standard C++ does not specify that dereferencing a NULL pointer throws an exception - it says it results in undefined behaviour. On Windows platforms, the water is muddied somewhat by Windows Structured Exception Handling. This has nothing to do with C++ exception handling, except that some C++ run-times may translate these excptions into C++ exceptions. However, code that depends on such translations is not portable.
try {
int * i = NULL;
*i = 3;
}
catch (...) {
// This would catch the access violation but you don't have any more
// information of what has gone wrong
}
You can however, use structured exception handling (SEH) to catch all C++ exceptions. Since C++ exceptions are just a class based implementation based on SEH.