try, catch handling doesn't work - exception

it's my first time developing windows phone app so...
I'm using try and catch in handling my exception but in the run the codes inside the try block didn't work !!
I'm sure that the inside codes are right but why it's not going inside :/
that's my code:
double amount =1 ;
try
{
amount = Convert.ToDouble(textBlock1);
}
catch (Exception) { }

I suppose you are trying to convert the text in textBlock1 to a double. What you are actually do is converting the TextBlock instance to a double. That doesn't make sense. This should do what you want:
amount = Convert.ToDouble(textBlock1.Text);
Understanding this problem is basic C#, so first you should learn more C# and .NET, than wp7 development will be much easier.

Related

How to manipulate ParseException in Javacc

I have created a lexer and parser in javacc and I am trying to handle errors. I initially tried using try-catch blocks for each symbol that is missing in the parser but I read online something about catching the ParseException only once in the main block with a try-catch and manipulating it to get the last token read and next token and more similar things. I am trying to know more about it but I did not come across anything else as most places use try-catch blocks.
Till now, I know I can do : e.currentToken.image if I catch (ParseException e) and also e.getErrorOffset(), but would like to know if there are other methods that can be used to print a more human-readable and informative error. If anyone has any examples or could direct me to some document.Thanks in advance.
The best way to get better (or different) error messages may be to modify the ParseException class itself.

How to use JSON Utility to Import Data from Browser to Unity?

I am just getting started programming and I couldn’t wrap my head around the following problem I currently have:
I have a PHP Script which retrieves the CPU Temperature of a Raspberry Pi and shows it on a local Network in my browser. The output in my browser is just a blank page with the value e.g. 56.7 only and no more.
What I would like to know now is, if it’s possible with JSON Utility to take this value and import it into Unity -> to be more specific, into an Augmented Reality Environment using Vuforia, even if it’s on a local Network and the only output is just the temperature value.
Is there anyone who could answer these (probably trivial) questions and eventually could show me how the code could look like?
And is it correct to assume, that the value within Unity would change as soon as the value in my browser changes?
I would like to thank everyone in advance for any help at all and even though these questions seem obvious for experienced programmers, I wasn’t able to find a correct answer by now.
Best regards!
Use UnityWebRequest to contact your Raspberry Pi.
Parse the DownloadHandler.text any way you like. JSON Utility is one option for parsing the result, but it might be overkill if this is a hobby project that just gets one sensor value.
https://docs.unity3d.com/Manual/UnityWebRequest-RetrievingTextBinaryData.html
To parse the json with JsonUtility, you would make a class to hold the data, making sure to mark it with Serializable attribute.
[System.Serializable]
public class MyData
{
public float temperature;
}
And then parse it like this, in the RetrievingTextBinaryData example
MyData myData = JsonUtility.FromJson<MyData>(www.downloadHandler.text)
Assuming your JSON looks like this
{ "temperature":30.7 }
Note: to make it continuously poll your Raspberry Pi for updates, you would need to download the temperature in the Update() method instead of Start() like in the example code.

How to fix ConnectionPoolTimeoutException in Apache Http Client

In our code we use version 4.5.3 of apache http client. PoolingHttpClientConnectionManager is used as follows.
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
600_000, TimeUnit.MILLISECONDS);
I understand that in order to fix ConnectionPoolTimeoutException, we either need to call EntityUtils.consume(httpEntity), or use ResponseHandler wherever HttpClient is used. However in our code base, the same HttpClient is being used from many places. After fixing much code to use either of the above two, the frequency is reduced, but we still get ConnectionPoolTimeoutException at times.
Can this exception be fixed by using evictExpiredConnections() or evictIdleConnections(maxIdleTime) methods while creating HttpClientBuilder? What is the ideal value of maxIdleTime that we can use - more than connectionTimeToLive?
One of the code example is as follows.
final HttpResponse resp ;
try
{
resp = client.execute(request);
}
catch (IOException e)
{
logException(e);
return;
}
processResponse(resp);
return;
We noticed a correlation between logException invocations & ConnectionPoolTimeoutException in the logs. In other words ConnectionPoolTimeoutException starts happening on a node, shortly after there are number of logException calls on that node. Is there something wrong with this code snippet?
Finally the solution was to use ResponseHandler wherever we had missed it. That was the only approach that worked, and solved ConnectionPoolTimeoutExceptions.
In an enterprise application, you cannot just close the HttpClient after each use. Using ResponseHandler is the best coding practice.

Windows Service Error Event

In ASP.Net I can use a http handler or module to catch errors.
I need something equivalent for my windows service.
I'm thinking something like Application.OnError += ErrorHandlingMethod;
Any ideas?
The asp.net features this possibility, as it has a complex execution pipeline, where you want to catch a general error.
This is not the case in windows services, as it only provides you the OnStart method, to start your service stuff.
that also means, that you can easily wrap everything in there with a try ... catch block.
so no need for a general error handling method.
if you want it even more general, than go to the Program.cs, and add that catch block there...

Why are empty catch blocks a bad idea? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I've just seen a question on try-catch, which people (including Jon Skeet) say empty catch blocks are a really bad idea? Why this? Is there no situation where an empty catch is not a wrong design decision?
I mean, for instance, sometimes you want to get some additional info from somewhere (webservice, database) and you really don't care if you'll get this info or not. So you try to get it, and if anything happens, that's ok, I'll just add a "catch (Exception ignored) {}" and that's all
Usually empty try-catch is a bad idea because you are silently swallowing an error condition and then continuing execution. Occasionally this may be the right thing to do, but often it's a sign that a developer saw an exception, didn't know what to do about it, and so used an empty catch to silence the problem.
It's the programming equivalent of putting black tape over an engine warning light.
I believe that how you deal with exceptions depends on what layer of the software you are working in: Exceptions in the Rainforest.
They're a bad idea in general because it's a truly rare condition where a failure (exceptional condition, more generically) is properly met with NO response whatsoever. On top of that, empty catch blocks are a common tool used by people who use the exception engine for error checking that they should be doing preemptively.
To say that it's always bad is untrue...that's true of very little. There can be circumstances where either you don't care that there was an error or that the presence of the error somehow indicates that you can't do anything about it anyway (for example, when writing a previous error to a text log file and you get an IOException, meaning that you couldn't write out the new error anyway).
I wouldn't stretch things as far as to say that who uses empty catch blocks is a bad programmer and doesn't know what he is doing...
I use empty catch blocks if necessary. Sometimes programmer of library I'm consuming doesn't know what he is doing and throws exceptions even in situations when nobody needs it.
For example, consider some http server library, I couldn't care less if server throws exception because client has disconnected and index.html couldn't be sent.
Exceptions should only be thrown if there is truly an exception - something happening beyond the norm. An empty catch block basically says "something bad is happening, but I just don't care". This is a bad idea.
If you don't want to handle the exception, let it propagate upwards until it reaches some code that can handle it. If nothing can handle the exception, it should take the application down.
I think it's okay if you catch a particular exception type of which you know it's only going to be raised for one particular reason, and you expect that exception and really don't need to do anything about it.
But even in that case, a debug message might be in order.
There are rare instances where it can be justified. In Python you often see this kind of construction:
try:
result = foo()
except ValueError:
result = None
So it might be OK (depending on your application) to do:
result = bar()
if result == None:
try:
result = foo()
except ValueError:
pass # Python pass is equivalent to { } in curly-brace languages
# Now result == None if bar() returned None *and* foo() failed
In a recent .NET project, I had to write code to enumerate plugin DLLs to find classes that implement a certain interface. The relevant bit of code (in VB.NET, sorry) is:
For Each dllFile As String In dllFiles
Try
' Try to load the DLL as a .NET Assembly
Dim dll As Assembly = Assembly.LoadFile(dllFile)
' Loop through the classes in the DLL
For Each cls As Type In dll.GetExportedTypes()
' Does this class implement the interface?
If interfaceType.IsAssignableFrom(cls) Then
' ... more code here ...
End If
Next
Catch ex As Exception
' Unable to load the Assembly or enumerate types -- just ignore
End Try
Next
Although even in this case, I'd admit that logging the failure somewhere would probably be an improvement.
Per Josh Bloch - Item 65: Don't ignore Exceptions of Effective Java:
An empty catch block defeats the purpose of exceptions
At the very least, the catch block should contain a comment explaining why it is appropriate to ignore the exception.
Empty catch blocks are usually put in because the coder doesn't really know what they are doing. At my organization, an empty catch block must include a comment as to why doing nothing with the exception is a good idea.
On a related note, most people don't know that a try{} block can be followed with either a catch{} or a finally{}, only one is required.
An empty catch block is essentially saying "I don't want to know what errors are thrown, I'm just going to ignore them."
It's similar to VB6's On Error Resume Next, except that anything in the try block after the exception is thrown will be skipped.
Which doesn't help when something then breaks.
This goes hand-in-hand with, "Don't use exceptions to control program flow.", and, "Only use exceptions for exceptional circumstances." If these are done, then exceptions should only be occurring when there's a problem. And if there's a problem, you don't want to fail silently. In the rare anomalies where it's not necessary to handle the problem you should at least log the exception, just in case the anomaly becomes no longer an anomaly. The only thing worse than failing is failing silently.
Empty catch blocks are an indication of a programmer not knowing what to do with an exception. They are suppressing the exception from possibly bubbling up and being handled correctly by another try block. Always try and do something with the exception you are catching.
I think a completely empty catch block is a bad idea because there is no way to infer that ignoring the exception was the intended behavior of the code. It is not necessarily bad to swallow an exception and return false or null or some other value in some cases. The .net framework has many "try" methods that behave this way. As a rule of thumb if you swallow an exception, add a comment and a log statement if the application supports logging.
If you dont know what to do in catch block, you can just log this exception, but dont leave it blank.
try
{
string a = "125";
int b = int.Parse(a);
}
catch (Exception ex)
{
Log.LogError(ex);
}
Because if an exception is thrown you won't ever see it - failing silently is the worst possible option - you'll get erroneous behavior and no idea to look where it's happening. At least put a log message there! Even if it's something that 'can never happen'!
I find the most annoying with empty catch statements is when some other programmer did it. What I mean is when you need to debug code from somebody else any empty catch statements makes such an undertaking more difficult then it need to be. IMHO catch statements should always show some kind of error message - even if the error is not handled it should at least detect it (alt. on only in debug mode)
It's probably never the right thing because you're silently passing every possible exception. If there's a specific exception you're expecting, then you should test for it, rethrow if it's not your exception.
try
{
// Do some processing.
}
catch (FileNotFound fnf)
{
HandleFileNotFound(fnf);
}
catch (Exception e)
{
if (!IsGenericButExpected(e))
throw;
}
public bool IsGenericButExpected(Exception exception)
{
var expected = false;
if (exception.Message == "some expected message")
{
// Handle gracefully ... ie. log or something.
expected = true;
}
return expected;
}
Generally, you should only catch the exceptions you can actually handle. That means be as specific as possible when catching exceptions. Catching all exceptions is rarely a good idea and ignoring all exceptions is almost always a very bad idea.
I can only think of a few instances where an empty catch block has some meaningful purpose. If whatever specific exception, you are catching is "handled" by just reattempting the action there would be no need to do anything in the catch block. However, it would still be a good idea to log the fact that the exception occurred.
Another example: CLR 2.0 changed the way unhandled exceptions on the finalizer thread are treated. Prior to 2.0 the process was allowed to survive this scenario. In the current CLR the process is terminated in case of an unhandled exception on the finalizer thread.
Keep in mind that you should only implement a finalizer if you really need one and even then you should do a little as possible in the finalizer. But if whatever work your finalizer must do could throw an exception, you need to pick between the lesser of two evils. Do you want to shut down the application due to the unhandled exception? Or do you want to proceed in a more or less undefined state? At least in theory the latter may be the lesser of two evils in some cases. In those case the empty catch block would prevent the process from being terminated.
I mean, for instance, sometimes you want to get some additional info from somewhere (webservice, database) and you really don't care if you'll get this info or not. So you try to get it, and if anything happens, that's ok, I'll just add a "catch (Exception ignored) {}" and that's all
So, going with your example, it's a bad idea in that case because you're catching and ignoring all exceptions. If you were catching only EInfoFromIrrelevantSourceNotAvailable and ignoring it, that would be fine, but you're not. You're also ignoring ENetworkIsDown, which may or may not be important. You're ignoring ENetworkCardHasMelted and EFPUHasDecidedThatOnePlusOneIsSeventeen, which are almost certainly important.
An empty catch block is not an issue if it's set up to only catch (and ignore) exceptions of certain types which you know to be unimportant. The situations in which it's a good idea to suppress and silently ignore all exceptions, without stopping to examine them first to see whether they're expected/normal/irrelevant or not, are exceedingly rare.
There are situations where you might use them, but they should be very infrequent. Situations where I might use one include:
exception logging; depending on context you might want an unhandled exception or message posted instead.
looping technical situations, like rendering or sound processing or a listbox callback, where the behaviour itself will demonstrate the problem, throwing an exception will just get in the way, and logging the exception will probably just result in 1000's of "failed to XXX" messages.
programs that cannot fail, although they should still at least be logging something.
for most winforms applications, I have found that it suffices to have a single try statement for every user input. I use the following methods: (AlertBox is just a quick MessageBox.Show wrapper)
public static bool TryAction(Action pAction)
{
try { pAction(); return true; }
catch (Exception exception)
{
LogException(exception);
return false;
}
}
public static bool TryActionQuietly(Action pAction)
{
try { pAction(); return true; }
catch(Exception exception)
{
LogExceptionQuietly(exception);
return false;
}
}
public static void LogException(Exception pException)
{
try
{
AlertBox(pException, true);
LogExceptionQuietly(pException);
}
catch { }
}
public static void LogExceptionQuietly(Exception pException)
{
try { Debug.WriteLine("Exception: {0}", pException.Message); } catch { }
}
Then every event handler can do something like:
private void mCloseToolStripMenuItem_Click(object pSender, EventArgs pEventArgs)
{
EditorDefines.TryAction(Dispose);
}
or
private void MainForm_Paint(object pSender, PaintEventArgs pEventArgs)
{
EditorDefines.TryActionQuietly(() => Render(pEventArgs));
}
Theoretically, you could have TryActionSilently, which might be better for rendering calls so that an exception doesn't generate an endless amount of messages.
You should never have an empty catch block. It is like hiding a mistake you know about. At the very least you should write out an exception to a log file to review later if you are pressed for time.