the name 'when' does not exist in the context - exception

I tried implementing the exception filters in C#.
try
{
//do Stuffs
}
catch (Exception ex) when (ex is System.Net.Sockets.SocketException || ex is SomeException);
{
//Handle the caught errors
}
I get an error saying, the name 'when' does not exist in the context with a red squiggly line under the word 'when'.
I even checked the version of c#, it is C# 6.

Related

How can i cover Junit test for an Exception's root cause?

I have the following block of code for which I want to increase code coverage:
try{
discountReferenceCustomerRepository.saveAllAndFlush(discountReferenceCustomersNew);
} catch (DataIntegrityViolationException ex) {
if(ex.getRootCause() != null && ex.getRootCause().toString().contains("Duplicate entry")){
LOGGER.error("{}::{}:: Attempt to persist duplicate data : [{}]", CdfConstants.CDF_CORE_SERVICE_NAME, DUPLICATE_DATA_ERROR, ex);
throw new SystemException("Attempt to persist one or more duplicate records ",ERROR_MSG_DUPLICATE_DATA);
} else {
throw ex;
}
}
return new ResponseStatusVO("Added new ORG to existing RCD for given EA");
}
I am unable to cover the "ex.getRootCause()" section, because in my Junit test, all i do is:-
when(repository.saveAllAndFlush(any())).thenThrow(new DataIntegrityViolationException("test"));
The root exception is SQLIntegrityConstraintViolationException with the message that says "Duplicate Entry". This error is then propagated by DataIntegrityViolationException which i can catch in my code.
Obviously, i am unable to do something like "ex.setRootCause" in my Junit coz there ain't such api defined in the library.
What can i do to increase coverage ?

throw .net-wrappable exception from native COM-Dll

In a native-C++-Dll (MFC): how to throw an Exception (with some additional text) that can be catched and handled from a .NET-Client?
This is the native-MFC-Dll which wants to throw an Exception:
void RGaugeTVDDataReader::LoadDataFromFile_HandleException(const CString& szPath) const
{
CString sMessage;
sMessage.Format(_T("TVD-File %s"), static_cast<LPCTSTR>(szPath));
/*1*/ AfxThrowFileException(CFileException::genericException, -1, static_cast<LPCTSTR>(sMessage));
/*2*/ throw std::runtime_error(CT2A(sMessage));
}
The Caller is a .Net-Dll which uses the native dll via a .net-generated-COM-Wrapper.
Both variants (/1/ and /2/) fall into the catch-Block of the .Net-Component but what I get here is just a ´System.Runtime.InteropServices.SEHException´ and the exceptionmessage says "External component has thrown an exception.". Included ErrorCode and HResult is 0x80004005. There is no inner exception, nothing to find about my given text and the stacktrace only contains the managed part.
So the question is: how to throw an excpetion from the native-c++-dll so that a .net-client using it via COM can at least see the message-string?
Alternative question: how to catch and handle the thrown exception in .net correctly?
regards

AssertJ assert on Exception covered another Exception

I'm a beginner of AssertJ. I encountered some issue when I use AssertJ to do Unit Testing.
JAVA: version 8
AssertJ: 3.11.1
I have a source code as below, to capture an exception and throw another exception.
try {
Integer.valueOf(valueA);
} catch(Exception e) {
throw new XXXException("value is not valid", e);
}
My test case as below failed, and I was told wrong exception assert, it's a bit confusing.
Throwable thrown = catchThrowable(() -> {
contract.init(ctx, "A", "100A", "B", "200");
});
assertThat(thrown).isInstanceOf(XXXException.class);
The error message as below, it seems like the original exception was captured by AssertJ. Anyone can help? Is it a bug or my mistake of AssertJ API usage? Many Thanks.
java.lang.AssertionError:
Expecting:
<java.util.IllegalFormatConversionException: d != java.lang.String>
to be an instance of:
<xxxx.XXXException>
but was:
<"java.util.IllegalFormatConversionException: d != java.lang.String
Here's my attempt to reproduce the issue, the test passes as expected:
#Test
public void test() {
Throwable thrown = catchThrowable(() -> f());
assertThat(thrown).isInstanceOf(RuntimeException.class);
}
private void f() {
try {
Integer.valueOf("100A");
} catch (Exception e) {
throw new RuntimeException("value is not valid", e);
}
}
Can you show us what contract.init is doing?
Another possibility would be in the stack trace, if it contains a %d somewhere stack trace it might be interpreted by a String.format but hard to say without more details.

How to throw SystemException in java?

I saw many people wrote like:
try {
//something
}
catch (IOException e){
throw new SystemException("IO Error", e);
}
I got "Cannot instantiate the type SystemException" error and it seems SystemException is a abstract class, how can I able to throw it?
Yes, it is an abstract class and that means that it does not make sense to construct an object of type SystemException. It is recommended to use more meaningful exceptions types.
You have mentioned IOException in your code. This means an exception related to an I/O operation and the catcher can act accordingly (maybe a special log level, some I/O cleanup etc.).
In your particular case, I think you should change it to:
try {
//something
}
catch (IOException e) {
// log exception info and other context information here
// e.g. e.printStackTrace();
// just rethrowing the exception (call stack is still there)
throw e;
}
P.S. Quite offtopic, but coming from .NET world I have found about the subtle difference between throw ex; in C# vs. Java.

Why not every type are throw exceptions?

"Only the types that are inherited from the Throwable class can be thrown".
Could anybody explain me. Why not every type are throwable? If in doc there no mention about function can throw exception, it's mean that it do not have exception?
For example I thought that next try-catch block would work. But it is not.
try
{
writeln("(((((((((");
latestdtonpage = dts.sort!((a,b) => a>b).front; //latest date-time. from page.
}
catch(Exception e)
{
writeln("Can't select the latest Date from parsed date");
writeln(e);
}
But output in case of exception is next (no exception text):
(((((((((
core.exception.AssertError#C:\D\dmd2\windows\bin\..\..\src\phobos\std\array.d(73
9): Attempting to fetch the front of an empty array of DateTime
----------------
0x0051C4C9 in _d_assert_msg
0x00468E78 in pure nothrow ref #property #nogc #safe std.datetime.DateTime std.r
ange.__T11SortedRangeTAS3std8datetime8DateTimeS473app19StackOverflowParser5parse
MFAyaZ9__lambda2Z.SortedRange.front() at C:\D\dmd2\windows\bin\..\..\src\phobos\
std\range.d(8418)
0x0044F908 in void app.StackOverflowParser.parse(immutable(char)[]) at D:\code\T
rendoMetr\source\app.d(173)
0x0044F700 in app.StackOverflowParser app.StackOverflowParser.__ctor(app.DBConne
ct) at D:\code\TrendoMetr\source\app.d(150)
0x0044F199 in _Dmain at D:\code\TrendoMetr\source\app.d(33)
0x0052EDCA in D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ6runAllMFZ9__lambda1MFZv
0x0052ED9F in void rt.dmain2._d_run_main(int, char**, extern (C) int function(ch
ar[][])*).runAll()
0x0052ECB5 in _d_run_main
0x00470198 in main
0x005667D1 in mainCRTStartup
0x76D1336A in BaseThreadInitThunk
0x772A9F72 in RtlInitializeExceptionChain
0x772A9F45 in RtlInitializeExceptionChain
Error executing command run: Program exited with code 1
How I can throw exception in this code?
Your code throws an AssertError, indicating that dts.sort!((a,b) => a>b) is empty, and you shouldn't call .front on it. Instead, query .empty first, and act accordingly when it's true.
AssertError inherits from Error which in turn inherits from Throwable but not from Exception. So catch(Exception e) doesn't catch it. And you should not catch Errors anyway, as they indicate that the program is in an unrecoverable error-state.
AssertError in particular signals a logic bug in your program. Here: calling .front on an empty range. Don't catch AssertError, but fix your code instead.