How to set alert instead of showing unhandled exception in J2ME? - java

I am designing an application which shows unhandled exception due to lot of reason. So I want my application to show alert in catch block instead.

You could do something like this:
private Alert alert;
private Display display;
// Obtain display with display = Display.getDisplay(this); in consturctor
catch(Exception e) {
alert = new Alert("Error occurred", "Message: " + e.getMessage(), null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, form);
}
Hope this helps.

I think you can just put the alert handling in the catch block:
catch(Exception e) {
// create new alert and
}

The problem I think this guy is having, is that the exceptions are appearing seemingly randomly, i.e. he won't know which piece of code is throwing it.
Some J2ME handsets (e.g. Nokias) have a habit of showing the exception name to the user in an alert, while others (e.g. Sony Ericssons) silently swallow them.
You need to identify all the points at which code can be executed (i.e. all the threads you're creating, and all the MIDP lifecycle methods that the framework could be calling for you), and wrap all of those in try/catch blocks, to ensure that no exceptions can be shown in this way.
That will probably slow your code down a lot though, so you should get to the bottom of what causes these exceptions to appear, and fix the problem!

Related

Try/Catch isn't catching my null Image exception from URL in JavaFX

Okay so, I have a Circle component which I assigned in SceneBuilder. I want to fill this Circle with an ImagePattern object, however I'm running into a weird problem. I'm assigning a lot of images from lots of URL's in a database and they're only set when I click them, and some of the links appear to be broken, but for some reason I can't prevent my program from crashing using try/catch.
Here are examples of working links:
https://a0.muscache.com/im/users/67564/profile_pic/1320663729/original.jpg?aki_policy=profile_x_medium
https://a0.muscache.com/im/users/168920/profile_pic/1279390466/original.jpg?aki_policy=profile_x_medium
https://a0.muscache.com/im/users/502496/profile_pic/1385405597/original.jpg?aki_policy=profile_x_medium
Here is an example of a link which crashes my program:
https://a0.muscache.com/im/pictures/c5b5bc4e-0133-4103-b68e-66f33bbf9e27.jpg?aki_policy=profile_x_medium
As you can see the link leads to a Null directory, and I get this error in my console:
Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: Image must be non-null
So I assumed I could fix this with a simple try/catch, so I did the following:
try {
circle.setFill(new ImagePattern(new Image("https://a0.muscache.com/im/pictures/c5b5bc4e-0133-4103-b68e-66f33bbf9e27.jpg?aki_policy=profile_x_medium")));
}
catch (Exception e){
e.printStackTrace();
}
And nada, it doesn't catch my error. I've tried using the correct IllegalArgumentException catch, I've tried ignore the catch, no differences.
I've made a mini recreation of my problem below and the error is still prevalent:
public class Test extends Application {
#Override
public void start(Stage stage){
BorderPane root = new BorderPane();
Circle circle = new Circle(50);
root.setCenter(circle);
// Works fine (Working link)
//circle.setFill(new ImagePattern(new Image("https://a0.muscache.com/im/users/67564/profile_pic/1320663729/original.jpg?aki_policy=profile_x_medium")));
// Dies and cries (Broken link)
try {
circle.setFill(new ImagePattern(new Image("https://a0.muscache.com/im/pictures/c5b5bc4e-0133-4103-b68e-66f33bbf9e27.jpg?aki_policy=profile_x_medium")));
}
catch (Exception e){
e.printStackTrace();
}
scene = new Scene(root);
stage.setTitle("test");
stage.setScene(scene);
stage.show();
}
}
Just to affirm what my goal is, I just want my program to completely ignore this line if the link is invalid, how would I do this? Thanks.
Also in case there's any confusion as to why I'm trying to load a dead link, as I said before I'm loading images from a database so I have no idea which links work and which don't, and I don't know how to check and researching just seems to tell me to use a try/catch.
Okay nevermind I found how to fix it, there's a method in Image for checking if there's an error:
image.isError()

Correct way to use Logs debug in android? Breakpoint

My app is currently crashing on start I only have one class MainActivity I'm trying to figure out what causing it
I found that there is multiple Log
Log.v(); // Verbose Log.d(); // Debug Log.i(); // Info Log.w(); // Warning Log.e(); // Error
Which one should I use ? and what about Breakpoint should I check every entry method ?
I tried implementing like this I'm not sure if it's the best or right way
try{
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog();
}
});
catch (Exception ex)
{
Log.e("I shouldn't be here", ex.getMessage());
}
If you look at the logcat stacktrace, it already should tell you what caused the exception. You should only need to set breakpoints around where the exception happens
As for which level of logging you need, it is up to you to determine the severity & verbosity of the message. Info is a general print, error is critical, warn is somewhere in between and debug is for putting lots of details. And Log.wtf is just for laughs 😁 (although the actual reason is mentioned in the documentation)
Rather than using the default Log class, consider using Timber.
Remember, whenever you log in production a puppy dies. 🐶🐶🐶☠️

Android exception handling best practice?

If my app crashes, it hangs for a couple of seconds before I'm told by Android that the app crashed and needs to close. So I was thinking of catching all exceptions in my app with a general:
try {
// ...
} catch(Exception e) {
// ...
}
And make a new Activity that explains that the application crashed instantly (and also giving users an opportunity to send a mail with the error details), instead of having that delay thanks to Android. Are there better methods of accomplishing this or is this discouraged?
Update: I am using a Nexus 5 with ART enabled and I am not noticing the delay I used to experience with apps crashing (the "hanging" I was talking about originally). I think since everything is native code now, the crash happens instantly along with getting all the crash information. Perhaps the Nexus 5 is just quick :) regardless, this may not be a worry in future releases of Android (given that ART is going to be the default runtime in Android L).
Here, check for the link for reference.
In here you create a class say ExceptionHandler that implements java.lang.Thread.UncaughtExceptionHandler..
Inside this class you will do your life saving stuff like creating stacktrace and gettin ready to upload error report etc....
Now comes the important part i.e. How to catch that exception.
Though it is very simple. Copy following line of code in your each Activity just after the call of super method in your overriden onCreate method.
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
Your Activity may look something like this…
public class ForceClose extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
setContentView(R.layout.main);
}
}
You could just use a generic alert dialog to quickly display error messages.
For example...
//******************************************
//some generic method
//******************************************
private void doStuff()
{
try
{
//do some stuff here
}
catch(Exception e)
{
messageBox("doStuff", e.getMessage());
}
}
//*********************************************************
//generic dialog, takes in the method name and error message
//*********************************************************
private void messageBox(String method, String message)
{
Log.d("EXCEPTION: " + method, message);
AlertDialog.Builder messageBox = new AlertDialog.Builder(this);
messageBox.setTitle(method);
messageBox.setMessage(message);
messageBox.setCancelable(false);
messageBox.setNeutralButton("OK", null);
messageBox.show();
}
You could also add other error handling options into this method, such as print stacktrace
i found the "wtf" (what a terrible failure) method in the Log class. From the description:
Depending on system configuration, a report may be added to the
DropBoxManager and/or the process may be terminated immediately with
an error dialog.
http://developer.android.com/reference/android/util/Log.html

SWT - MessageDialog - Shells

I have an operations class that has no gui. The class basically does data management. The class is called from a method in my Main GUI. The problem I am having is with displaying messages to the user if something fails. I am using MessageDialog, but it keeps failing at runtime. I think the issue is with Shell. When I try to use null as the shell.
MessageDialog.openError(null, "Printer Error Message", "Error getting print reply file.");
The error is null pointer exception
MessageDialog.openError(Display.getCurrent().getActiveShell() etc
The error is null pointer exception
MessageDialog.openError(Display.getDefault().getActiveShell()
The error is invalid thread access
Being this is not a GUI class, do I have to pass in the shell from the GUI parent?
Can I just create a shell in the class and then use that?
You can fix the ERROR_THREAD_INVALID_ACCESS error with Display.syncExec or Display.asyncExec . Try with:
Display.syncExec(new Runnable() {
void run() {
MessageDialog.openError(Display.getDefault().getActiveShell()...
}
}
This will do what you want:
MessageDialog.openError(new Shell(), "Printer Error Message", "Error getting print reply file.");
Just create a new Shell and pass it to the MessageDialog.
Few important points to consider.
First of all, do not mix Data Management classes(models) with UI.
Have a utility class and methods to show errors/info messages.
always access UI widgets in UI thread. Use Display.getDefault().asyncExec() or syncExce()
Check Display.getDefault().getActiveShell() to pass it to the
dialog first, if it is null, create one and pass it.

Handling java errors

I linked sqlite to java. I want to show a pop up frame to user if there is an error with database but all errors appear in console! how can I manage them?
try
{
DataBase.databaseConnect("Test");
DataBase.databaseDataQuery(data);
DataBase.databaseDisconnect();
}catch(SQLException e)
{
JOptionPane a=new JOptionPane();
a.showMessageDialog(getParent(), "error");
}
catch SQLException
use JOptionPane.showMessageDialog(..) to show a message
Note that you should only tell the end-user that a problem exists. He doesn't care whether that you have a constraint violation, or a missing column.
The whole stacktrace should be logged to a file, or sent directly to you (the vendor)
Try using JOptionPane.showMessageDialog(....)
http://download.oracle.com/javase/6/docs/api/javax/swing/JOptionPane.html

Categories