Custom Exception not caught, but unhandled - exception

I have a custom exception class that inherits Exception.
In my Try-Catch block I have a line of code that causes an InvalidCastException.
But the exception is always unhandled at the code line that caused it and not caught by the Catch block.
Public Class InvalidPremiumException
Inherits System.Exception
Public Sub New()
End Sub
Public Sub New(message As String)
MyBase.New(message)
End Sub
Public Sub New(message As String, inner As Exception)
MyBase.New(message, inner)
End Sub
End Class
Then in another class:
Try
' code that causes an InvalidCastException here
Catch ex As InvalidPremiumException
Console.WriteLine("Invalid or Missing Premium")
End Try

You are catching InvalidPremiumException in the Catch block. Only that exception will be caught in this block that is of type InvalidPremiumException or is inherited from it, others will go unhandled.
You may also consider using multiple catch blocks.
The InvalidCastException will be handled in the second Catch block:
Try
' code that causes an InvalidCastException here
Catch ex As InvalidPremiumException
Console.WriteLine("Invalid or Missing Premium")
Catch ex As Exception
Console.WriteLine("Catching other exceptions")
End Try
The Catch block will only handle those exceptions which are either of the same type or one of its children's type. That is why your custom exception is handled in the second block.

Related

What will happen if exception thrown of a particular type don't have a catch block corresponding to that exception in c++

For the code given below. How will the code behave and why?
// code goes here..
try {
if(a==0) throw "a is 0";
}
catch(int a) { ; }
a = 19;
//code goes here.....
Since you are throwing a string (aka const char*) but you are only catching values of type int, the exception will not be caught and will go on unwinding the function stack until it finds a try-block willing to catch your exception or it reaches main and aborts your program.
That is, if your catch block does not catch the thrown exception type it is as if it was not there.

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.

JUnit - Catch an exception in the #After section

I have this scenario in which some tests can throw different exceptions.
#Test
public void addDevice(){
device.addDevice(); // this may throw exception 1
device.verifyStatus("Ready");
device.open(); // this may throw exception 2
device.verifyStatus("Open");
}
#Test
public void otherTest(){
device.act(); // this may throw exception 3
device.verifyStatus("Ready");
}
#After
public void tearDown(){
// handle the exception here
}
I want to handle those exceptions in the #After section without wrapping the test with try, catch.
Is that possible?
No, it is not possible.
You could wrap the test anyway with a try-catch-block. Then you could store the exception to a member variable instead of handling it.
In the #After method you can check whether the exception is null or not.
Due to your comment that you have hundreds of tests with this code I assume that this is set up logic which should actually be in an #Before method.
Thus, you could specify an external resource rule with a before and after method: https://github.com/junit-team/junit/wiki/Rules#externalresource-rules
In the before() method you perform the set up, catch and store the exceptions and in the after() method you handle them.
But does it make sense to handle the exception later? Can you run your test cases successfully if the set up fails?

Handling wrapped exception in Camel

class MyRouteBuilder extends SpringRouteBuilder {
public void configure() throws Exception {
//initialize camel context here
onException(ChildException.class)
.process(new ChildExceptionHandler())
.handled(true)
.to(errorURI);
onException(ParentException.class)
.process(new ParentExceptionHandler())
.handled(true)
.to(errorURI);
from(startURI)
.processRef("someBeanID")
//other processing here
}
}
Now my "someBeanID" throws ChildException while processing, but ParentExceptionHandler is being invoked for that. Code snippet in "someBeanID" is as below
try {
//some processing
throws new ParentException();
} catch (ParentException e) {
throw new ChildException(e); //being handled by ParentExceptionHandler (why?? should be ChildExceptionHandler??)
throw new ChildException(); //being handled by ChildExceptionHandler (should be)
}
It seems that whenever we wrap any exception, Camel automatically finds the actual wrapped exception and invokes handler for that, instead of invoking handler for wrapper exception. Why is this? Is there any problem in my code ??
Thanks,
Finally resolved....Refer to this
When trapping multiple exceptions, the order of the onException clauses is significant. Apache Camel initially attempts to match the thrown exception against the first clause. If the first clause fails to match, the next onException clause is tried, and so on until a match is found. Each matching attempt is governed by the following algorithm:
If the thrown exception is a chained exception (that is, where an exception has been caught and rethrown as a different exception), the most nested exception type serves initially as the basis for matching. This exception is tested as follows:
If the exception-to-test has exactly the type specified in the onException clause (tested using instanceof), a match is triggered.
If the exception-to-test is a sub-type of the type specified in the onException clause, a match is triggered.
If the most nested exception fails to yield a match, the next exception in the chain (the wrapping exception) is tested instead. The testing continues up the chain until either a match is triggered or the chain is exhausted.

Grails error handler always receives null pointer

We have a custom error controller that gets called after all of our errors. However, most of our errors that get thrown end up coming into the controller as null pointers, even though the original error was not a null pointer. Any ideas? Code below. Bootstrap and UrlMappings available if needed. Thanks
Error Handler method
def HandleErrors =
{
def exception = request.exception.cause.class
if (exception)
{
Exception ex = request.exception //This exception is always a NPE
...
Block of code throwing the exception. I originally did not have a try catch in here, but wanted to add it so that I was sure the exception being thrown was Not a NPE. Its a file not found exception.
try{
def writer = new FileWriter( new File(fileSaveLocation));
}
catch ( ex)
{
throw(ex)
}
Edit: Adding the exception that is pushed to the exception handler
Exception:org.codehaus.groovy.grails.web.errors.GrailsWrappedRuntimeException
Cause:org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
It's not because you're referencing something that is null inside the error handler, and so are inadvertently throwing another exception, which is again caught?
can you try changing:
def exception = request.exception.cause.class
to
def exception = request?.exception?.cause?.class