I have the following code
Try
'Some code that causes exception
Catch ex as ExceptionType1
'Handle Section - 1
Catch ex as ExceptionType2
'Handle section - 2
Catch ex as ExceptionType3
'Handle section - 3
Finally
' Clean up
End Try
Suppose ExceptionType1 is thrown by the code which is handled by section - 1. After handling that in section-1, can I have control passed to section-2/section-3? Is that possible?
Change the code to catch all the exceptions in one block and determine the type and execution path from there.
You could call functions in the exception handlers.
Try
'Some code that causes exception'
Catch ex as ExceptionType1
handler_1()
handler_2()
handler_3()
Catch ex as ExceptionType2
handler_2()
handler_3()
Catch ex as ExceptionType3
handler_3()
Finally
handler_4()
End Try
You haven't specified a language, and i don't know the language, so i answer generally.
You can't do that. If you want to have common code, put that either into finally, or if it only needs to be executed for some catching cases, you can copy that code into the respective cases. If the code is bigger and you want to avoid redundancy, you can put it into a function of its own. If that would reduce the readability of your code, you can nest your try/catch blocks (at least in Java and C++. I don't know about your language). Here is an example in Java:
class ThrowingException {
public static void main(String... args) {
try {
try {
throw new RuntimeException();
} catch(RuntimeException e) {
System.out.println("Hi 1, handling RuntimeException..");
throw e;
} finally {
System.out.println("finally 1");
}
} catch(Exception e) {
System.out.println("Hi 2, handling Exception..");
} finally {
System.out.println("finally 2");
}
}
}
This will print out:
Hi 1, handling RuntimeException..
finally 1
Hi 2, handling Exception..
finally 2
put your common code into the outer catch block. Doing it using the nested version also handles cases where an exception occurs without you explicitly re-throwing the old in a catch block. It may fit to what you want even better, but it may also not.
I think you could get the behavior you want if you do nested try blocks. Once an exception is thrown, execution goes to the catch block. If nothing is rethrown, it moves on to finally.
Related
I'm still learning Kotlin and I just learned about the "use" and how it is a replacement for a try, catch and finally block.
However I am curious if it is possible to customize it's exception handling for example:
var connection: Connection? = null
try {
connection = dataSource.connection
connection.prepareStatement(query).execute()
} catch (e: SQLException) {
logger.log("Specific error for that query")
e.printStackTrace()
} finally {
if (connection != null && !connection.isClosed) {
connection.close()
}
}
That code is my current one, I have a specific error I would like to display on the catch, would that be possible using use?
This is my current use code:
dataSource.connection.use { connection ->
connection.prepareStatement(query).execute()
}
As commented by #Tenfour04, and from the documentation
[use] Executes the given block function on this resource and then closes it down correctly whether an exception is thrown or not.
In particular it is implemented like this:
public inline fun <T : AutoCloseable?, R> T.use(block: (T) -> R): R {
var exception: Throwable? = null
try {
return block(this)
} catch (e: Throwable) {
exception = e
throw e
} finally {
this.closeFinally(exception)
}
}
That piece of code should look familiar if you're a Java developer, but basically it executes block passing this (i.e. the receiver object) as an argument to your block of code. At the end it closes the AutoCloseable resource. If at any point an exception is thrown (either inside block or while closing the resource), that exception is thrown back to the caller, i.e. your code.
As an edge case you could have 2 exceptions, one when executing block and one when closing the resource. This is handled by closeFinally (whose source is available in the same file linked above) and the exception thrown while closing the resource is added as a suppressed exception to the one thrown from block – that's because only up to 1 exception can be thrown by a method, so they had to choose which one to throw. The same actually applies to the try-with-resources statement in Java.
prinBalAgencyComm.sendKeys(testData.get("agencyCommissionPB"));
prinBalClientRem.sendKeys(Keys.TAB);
prinBalFrom2.sendKeys(testData.get("fromFB2")); //Locator not found
prinBalAgencyCommLast.sendKeys(testData.get("agencyCommissionLastPB")); //how to execute this line without fail
You can handle this by using try catch finally.
try{
//code that can result in an exception
prinBalAgencyComm.sendKeys(testData.get("agencyCommissionPB"));
prinBalClientRem.sendKeys(Keys.TAB);
prinBalFrom2.sendKeys(testData.get("fromFB2"));
}catch(Exception e)
{
//actions you want to take in case your locator isnt found or another exception occurs
System.out.println("Exception occured" + e.getMessage());
}finally
{ //the line to be executed without fail
prinBalAgencyCommLast.sendKeys(testData.get("agencyCommissionLastPB"));
}
you would have to implement a try/catch block
try {
element action
} catch (Exception e) {
//whatever you want to happen when it fails
}`
But I would ask myself why is the test not consistent with every run? Why should this step not pass every time?
One pattern you can use is:
try {}
catch {}
Place your offending code in the try block and any error code in the catch block.
If an exception is raised in the try, the catch block will be called instead of proceeding to the next line in the try
I am running Silverlight 4 with a MVVM framework. From time to time, but not always, during a detail page load, I get a XamlParseException. Since it works 99% of the time, I'm pretty sure the xaml page is fine.
Is it possible to do something similar to the following in my code behind page?
public DetailView() {
try {
InitializeComponent();
} catch (XamlParseException e) {
Debugger.Break();
}
}
In other words, how do I catch the XamlParseException?
You cannot catch this exception using try-catch when the parsing is being handled by the runtime.
The only way to catch this exception is when you are using XamlReader like in this discussion:
http://social.msdn.microsoft.com/Forums/da-DK/wpf/thread/02679567-1bd3-41d1-bfd1-326f646d95d1
You can try handling it on Application_UnhandledException.
More info here: http://msdn.microsoft.com/en-us/library/system.windows.application.unhandledexception(v=vs.95).aspx
And some more info here: http://msdn.microsoft.com/en-us/library/cc189070(v=vs.95).aspx
I'm using ANTLR3 with the C runtime.
I'd like to do some custom error handling. What I'm really after is that if there is an antlr matching exception of any kind in a sub rule I'd like to tell ANTLR to skip trying to handle it and let it percolate up to a more global rule.
At that rule I'll log it and then try to resume.
I've set the rule catch method like so, so that all rules won't try to recover.
#rulecatch
{
if (HASEXCEPTION())
{
PREPORTERROR();
}
}
This allows me to insert catch handlers on the rules that i want.
At my rule of interest i can then use the catch syntax like so:
catch [ANTLR3_RECOGNITION_EXCEPTION]
{
PREPORTERROR();
RECOGNIZER->consumeUntil(RECOGNIZER,RCURLY);
CONSUME();
PSRSTATE->error = ANTLR3_FALSE;
PSRSTATE->failed = ANTLR3_FALSE;
}
The problem is that this syntax seems to only allow me to catch one type of exception. I'd like to be able to catch all exception types.
Is there a way to do this?
I thought I could overload all the recovery functions but then some code generates exceptions like so:
CONSTRUCTEX();
EXCEPTION->type = ANTLR3_NO_VIABLE_ALT_EXCEPTION;
EXCEPTION->message = (void *)"";
EXCEPTION->decisionNum = 23;
EXCEPTION->state = 0;
goto rulewhenEx;
which means I'll need to catch all possible exceptions.
Any thoughts??
I've ended up trying two solutions for this.
Approach 1)
Overloading the rulecatch setting to set the exception type to one specific type
#rulecatch
{
if (HASEXCEPTION())
{
// This is ugly. We set the exception type to ANTLR3_RECOGNITION_EXCEPTION so we can always
// catch them.
PREPORTERROR();
EXCEPTION->type = ANTLR3_RECOGNITION_EXCEPTION;
}
}
This allows me to use one catch block as all exceptions will be of that type.
Approach 2)
I just use multiple catch blocks and they all dispatch to a common function to handle the error
catch [ANTLR3_RECOGNITION_EXCEPTION]
{
handleException();
}
catch [ANTLR3_MISMATCHED_TOKEN_EXCEPTION]
{
handleException();
}
....
In C# you can do this:
try
{
// some code here
}
catch (MyCustomException)
{
// exception code here
}
catch (Exception)
{
// catches all other exceptions
}
Notice the catch (Type) instead of catch (Type myVariable). Is this possible with VB.NET, or do you always have to declare a variable when you catch exception types, like so:
Try
...
Catch var As NullReferenceException
...
Catch var As Exception
...
End Try
Gotta be declared in vb.net.
In fact when you type in try your ide should put in the exception type and format it.
like so:
Try
Catch e As Exception
End Try
In case a search engine brings anybody else here...
C# also has a syntax where you don't have to specify the type:
try { }
catch { }
I believe that will also catch unmanaged exceptions that do not derive from System.Exception. VB.NET can do the same:
Try
Catch
End Try