How can I re-throw a CFileException? - exception

I know that I can re-throw a CFileException if I am inside a catch statement by using throw to bubble it up the chain.
But what about this:
CFile fileRPT;
CFileException ex;
if (!fileRPT.Open(L"SomeFile.txt", CFile::modeCreate | CFile::modeWrite, &ex))
{
ex.ReportError();
return;
}
It directly fills the CFileException object so I can't just use the keyword throw as we are not in a catch block.
If I try throw ex this is displayed:

The clue was in the online documentation, about using AfxThrowFileException.
So:
AfxThrowFileException(ex.m_cause, ex.m_lOsError, ex.m_strFileName);
Based on the comments I have changed to using a smart pointer:
auto ex = std::make_unique<CFileException>();
if (!fileRPT.Open(strFileName, CFile::modeCreate | CFile::modeWrite, ex.get()))
{
throw ex.release();
}

Related

Exception Handling between member functions of a class

Assume there are two member functions f1(), f2() of an object O2.
Consider below code.
O2::f2()
{
if(somestring.length()<20)
{
throw
}
}
O2::f1()
{
try
{
f2()
}
catch(...)
{
//Some handling
}
}
Here ideally f1 should catch exception thrown by exception. But it is not happening. Instead,
getting error as shown below:
Terminated without any active exception
This is because f2 has an empty throw statement. If that statement is executed without an active exception being handled, terminate is supposed to be called.You need to throw something in order to catch

In Kotlin exception blocks, how does one implement an 'else' (success) block?

In Python, I would do this:
try:
some_func()
except Exception:
handle_error()
else:
print("some_func was successful")
do_something_else() # exceptions not handled here, deliberately
finally:
print("this will be printed in any case")
I find this very elegant to read; the else block will only be reached if no exception was thrown.
How does one do this in Kotlin? Am I supposed to declare a local variable and check that below the block?
try {
some_func()
// do_something_else() cannot be put here, because I don't want exceptions
// to be handled the same as for the statement above.
} catch (e: Exception) {
handle_error()
} finally {
// reached in any case
}
// how to handle 'else' elegantly?
I found Kotlin docs | Migrating from Python | Exceptions, but this does not cover the else block functionality as found in Python.
Another way to use runCatching is to use the Result's extension functions
runCatching {
someFunc()
}.onFailure { error ->
handleError(error)
}.onSuccess { someFuncReturnValue ->
handleSuccess(someFuncReturnValue)
}.getOrDefault(defaultValue)
.also { finalValue ->
doFinalStuff(finalValue)
}
Take a look at the docs for Result: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/index.html
If you do not care about the default value, for example, you want just to hide the loading you could use this:
runCatching {
show_loading(true) //show loading indicator
some_func() //this could throw an exception
}.onFailure {
handle_error(it.message)
}.getOrNull().run {
show_loading(false) //hide loading indicator regardless error or success
}

Checking to see if a property exists without throwing exception yii2

Depending on database result, some properties of my object may be populated or not.
Lets say I have a task object and if there is a message for it, so it has the $message property populated:
if($task->message === null)
throw new ErrorException('what the ...');
The problem is, whenever I want to check if this property is populated (accessing it), it throws an Getting unknown property exception and the execution terminates.
I think you can try with isset
if (isset($task->message )) {
// your code for is setted
} else {
// your code for not setted
}
Try-catch block also works:
use yii\base\Exception;
[...]
try {
echo $task->message;
} catch (Exception $e) {
// stuff
}

Check APEX exception type

I'm looking to check what type of exception is retruned in the following code snippet.
I'm not sure exactly how to do it though, or if it's even possible.
try {
//SOME LOGIC
} catch (exception ex) {
System.debug(//EXCEPTION TYPE);
}
Would anyone have any suggestions or advice??
try {
//SOME LOGIC
} catch (Exception ex) {
System.err.println(ex.getClass().getName());
}
Few things:
You have posted exception. I assume you meant Exception.
System.debug does not exist.
I have answered your specific question but obviously this is not standard exception handling code. You will instead output the stacktrace, log the exception or rethrow a different one.
Firstly, within your catch block(s), specify the exception. Semantically, types including Exception are not in camel case.
Secondly, you can obtain the exception type through Exception.getClass().getName():
catch (Exception exception) {
System.out.println(exception.getClass().getName());
// exception.printStackTrace();
// throw exception;
}
Specified by:http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
After some searching around I found an answer,
try {
//SOME LOGIC
} catch (Exception ex) {
System.debug(ex.getTypeName());
}
The getTypeName() method does the trick nicely.
I apologise for not specifying I was working in Apex in my question.

Avoid throwing a new exception

I have an if condition which checks for value and the it throws new NumberFormatException
Is there any other way to code this
if (foo)
{
throw new NumberFormatException
}
// ..
catch (NumberFormatException exc)
{
// some msg...
}
If you are doing something such as this:
try
{
// some stuff
if (foo)
{
throw new NumberFormatException();
}
}
catch (NumberFormatException exc)
{
do something;
}
Then sure, you could avoid the exception completely and do the 'do something' part inside the conditional block.
If your aim is to avoid to throw a new exception:
if(foo)
{
//some msg...
} else
{
//do something else
}
Don't throw exceptions if you can handle them in another, more elegant manner. Exceptions are expensive and should only be used for cases where there is something going on beyond your control (e.g. a database server is not responding).
If you are trying to ensure that a value is set, and formatted correctly, you should try to handle failure of these conditions in a more graceful manner. For example...
if(myObject.value != null && Checkformat(myObject.Value)
{
// good to go
}
else
{
// not a good place to be. Prompt the user rather than raise an exception?
}
In Java, you can try parsing a string with regular expressions before trying to convert it to a number.
If you're trying to catch your own exception (why???) you could do this:
try { if (foo) throw new NumberFormatException(); }
catch(NumberFormatexception) {/* ... */}
if you are trying to replace the throwing of an exception with some other error handling mechanism your only option is to return or set an error code - the problem is that you then have to go and ensure it is checked elsewhere.
the exception is best.
If you know the flow that will cause you to throw a NumberFormatException, code to handle that case. You shouldn't use Exception hierarchies as a program flow mechanism.