Why doesn't this line of code work?
int display_width = display.getCurrent().getWidth();
When I start my midlet, I see this error: Exception. Application has unexpectedly quit. contact the application provider to resolve the issue. 0.
Why?
It's possible that something here is throwing an exception, but the library is hiding it behind that user friendly error message.
My guess is that display.getCurrent() is returning null, so the getWidth() causes a NullPointerException.
Try this:
Display myDisplay = display.getCurrent();
System.out.println(myDisplay);
int display_width = myDisplay.getWidth();
Note that you'll need to replace the Display class may whatever the type of display.getCurrent()'s return value is.
Or, better yet, you could try to catch the exception:
try {
int display_width = display.getCurrent().getWidth();
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
Related
I have a piece of code like this:
auto theval = myfunc();
dosomething(theval);
Now, I want to wrap the first part in a try/catch block:
try {
auto theval = myfunc();
} catch (const std::exception& ex){
// do some error handling
}
dosomething(theval);
Unfortunately, this doesn't work, because theval is inside the try scope.
The conventional way to solve this would be to just move the declaration outside the scope like this:
auto theval;
try {
theval = myfunc();
} catch (const std::exception& ex){
// do some error handling
}
dosomething(theval);
But this doesn't work either, because auto can't be used without an initialization.
Is there a way in which I can solve this without having to explicitly use the return type of myfunc and without having to move the call to dosomething inside the try block?
One possible solution is to use decltype like this:
decltype(myfunc()) theval;
try {
theval = myfunc();
} catch (const std::exception& ex){
// do some error handling
}
dosomething(theval);
perhaps augmented with std::remove_reference<...>::type to avoid issues with functions returning references.
(In case you're interested, the background for this question is here, but I don't think it's critical for this particular question.)
We're trying to run a series of report exports (a third party method call) one at a time in separate threads, so we can kill off the thread if it takes too long. The ugly, but best-so-far, idea is to use Thread.Abort to kill the thread exporting a given report, then do a ResetAbort to allow the rest of the code to continue.
The proof of concept code looks like this:
public RunningMethod()
{
Report myReport = new Report();
for (int i = 0; i < 10; i++)
{
Thread reportThread = new Thread(() => DoBackgroundJob(myReport, "test" + i.ToString()));
reportThread.Start();
bool finished = reportThread.Join(TimeSpan.FromMilliseconds(100));
if (!finished)
{
reportThread.Abort();
}
}
}
protected void DoBackgroundJob(Report myReport, string reportFilename)
{
try
{
report.ExportToPdf(#"C:\" + reportFilename + ".pdf");
}
catch (ThreadAbortException)
{
}
break;
}
I'm getting a strange result when I run this...the Export line seems to throw an exception that seems like it should be a ThreadAbortException, but apparently is not, since it doesn't get caught by the catch (ThreadAbortException), but is caught by a catch (Exception).
I'd like to know what kind of exception I'm getting, but I can't see it because when I try to view it I only get "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."
Is there a way to determine what is happening? What exception is really being thrown here?
I have a problem handling the end of file state of the axWindows Media Player and then open another frame in Visual C++
Here is my function :
private: System::Void axWindowsMediaPlayer1_PlayStateChange(System::Object^ sender, AxWMPLib::_WMPOCXEvents_PlayStateChangeEvent^ e) {
if (e->newState == 8) {
this->Hide();
MainForm^ frame = gcnew MainForm();
frame->ShowDialog();
}
}
If I build the project, the media player render the movie, plays it and when it reaches the end of file it's called the Hide function but the frame didn't show up. I receive no error.
What should I do or what I'm doing wrong ?
In this kind of situation you should try to catch an exception, and read its message - it's very helpful, and helps spare some time in the future.
try
{
...
}
catch (System::Exception^ e)
{
System::Console::WriteLine(e->Message);
}
I am trying to get to grips with C# having not coded for many years and my previous experience being in ANSI C.
I have read a number of books and searched online but one aspect is evading me and I am hoping someone here can help.
In the past I would declare a function and if there was a possibility of something not happening within the function (i.e. file not found etc.) declare the return to be an integer. I would then return 0 if all was well and a value if not. The value would correspond to where the function failed to execute fully and I could branch accordingly from where I called it.
if(function1())
{
// all my error stuff, maybe a switch/case etc.
}
All the examples I have found in C# seem to avoid this technique and I was hoping to get some understanding here.
Thanks in anticipation.
(I know I am a fossil). :)
Exceptions are the approach you use in C# and similar languages.
It goes like this:
try
{
function();
}
catch(FileNotFoundException e)
{
// File not found
}
catch(UnauthorizedAccessException e)
{
// User doesn't have right to access file
}
// etc...
To make this work, function shouldn't return a status code but instead throw an exception in case of an error.
Please note that the exceptions I illustrated in the code block above are thrown by the framework if you try to access a file and one of those errors is happening. So you don't actually have to do this yourself.
Furthermore, in C# there is no implicit conversion from integral values to bool, i.e. if(function()) is invalid, if function returns an int. You would need to write it like this:
if(function() != 0)
{
// all your error stuff
}
There's nothing to stop you doing this (though there are better ways of handling the errors - exceptions for example).
If you do want to carry on with this approach, the biggest problem you are having is that in C# you can't treat an integer as a boolean so your if test won't compile. What you need is:
if (function1() != 0)
{
}
But to check the value you'd need:
int result = function1();
switch (result)
{
case 1:
// Handle this case
break;
case 2:
// Handle this case
break;
default:
// All OK
break;
}
It would be better to return an enumerated type for each error case so that you don't have magic numbers, but exceptions are the way to go:
try
{
function1();
}
catch (SpecificException1 e1)
{
// Handle this case
}
catch (SpecificException2 e2)
{
// Handle this case
}
What you shouldn't have is a general exception handler:
catch (Exception e)
{
}
This just hides other potential problems.
If you want to follow that pattern of checking return value instead of managing errors, you better use enumarations than plain numbers.
For example:
public enum ResultType
{
Error = 0,
Success,
Waiting
}
public ResultType function()
{
if (still_waiting)
return ResultType.Waiting;
if (error_has_occured)
return ResultType.Error;
return ResultType.Success;
}
public void Main()
{
ResultType result = function();
switch (result)
{
case ResultType.Success:
MessageBox.Show("all is good");
break;
case ResultType.Waiting:
MessageBox.Show("still waiting...");
break;
case ResultType.Error:
MessageBox.Show("error has occurred");
break;
}
}
Behind the scenes, it's still using numbers but you put some meaning to each number.
if(function()==1)
{
}
int function()
{
int returnVal =0;
// do stuff
// if true return returnVal =1 else set returnVal =0;
return returnVal;
}
I have this problem converting object into string... I make use of the toString() function... and since the conversion of object into string were inside the try{}catch(exception e){}, i keep on receiving an output error: For input string: ""
What should be the problem if i keep on receiving an error message like that?
More elaboration:
the Object came from a jComboBox
which consists of items from a
database.
I am using a JFrame Form instead of
a Java Class.
All i want to do is to capture the selected Item from the JComboBox which happens to be an object. And then after capturing it. I'll use the value for my query in the database.
Here's my code(partial):
private void SUBMITActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName(Connect.DRIVER);
Connection con = DriverManager.getConnection(Connect.CONNECTION_STRING,
Connect.USERNAME, Connect.PASSWORD);
Object obj = jComboBox1.getSelectedItem();
String item_name = obj.toString();
int month = jMonthChooser.getMonth();
int q_box = Integer.parseInt(quantity_box_txtbox.getText());
double unit_price_box = 0;
int q_pc = Integer.parseInt(quantity_pc_txtbox.getText());
double unit_price_pc = 0;
double sub_total_box = 0;
double sub_total_pc = 0;
double grand_total = 0;
//Testing
System.out.println(jMonthChooser.getMonth());
System.out.println(item_name);
} catch (Exception e) {
System.out.println("Error: "+e.getMessage());
}
}
If you have anything you don't understand regarding with the way I explain my question please tell me... i'll try my best to elaborate further.
Thanks in advance.
:)
here's the complete error:
Error: java.lang.NumberFormatException : For input string: ""
Well, to start with:
Don't catch just Exception; catch specific subclasses
Don't just catch the exception; you almost certainly want to propagate it up to the caller
Don't log just the message - log the whole exception, including the stack trace and exception type.
The exception looks like it's trying to parse a string - not trying to convert an object to a string. I strongly suspect that the problem is one of these lines:
int q_box = Integer.parseInt(quantity_box_txtbox.getText());
int q_pc = Integer.parseInt(quantity_pc_txtbox.getText());
My guess is that one of the textboxes is empty - so you're effectively calling Integer.parseInt("") which is failing.