What is Exception in android....
There are three different situations that cause exceptions to be thrown: Exceptions due to programming errors: In this category, exceptions are generated due to programming errors (e.g., NullPointerException and IllegalArgumentException). The client code usually cannot do anything about programming errors.
Exceptions due to client code errors: Client code attempts something not allowed by the API, and thereby violates its contract. The client can take some alternative course of action, if there is useful information provided in the exception. For example: an exception is thrown while parsing an XML document that is not well-formed. The exception contains useful information about the location in the XML document that causes the problem. The client can use this information to take recovery steps.
Exceptions due to resource failures: Exceptions that get generated when resources fail. For example: the system runs out of memory or a network connection fails. The client's response to resource failures is context-driven. The client can retry the operation after some time or just log the resource failure and bring the application to a halt.
Before you begin to explore Android, you will need to be able to get information from your app and deal with errors.
Following Exception are occurred in android applications-
- Android :: AsyncTask And Exception Handling
- Android :: Handling Exception In A MediaFile App
- Android :: Out Of Memory Exception Handling?
- Android :: FileOutputStream And Exception Handling
- Android :: Exception Handling - Program Halts
- Android :: Handling Interrupted Exception Of AsyncTask?
- Android :: Handling Out Of Memory Exception On Image Processing
- Android :: How To Handle Throws Clause In Java Exception Handling
- Android :: Exception Handling - How To Catch Then Publish So That They Are Reported Via Market
- Android :: MyException Which Shows Toast Causes Trouble While Thrown In Threads - How Should Reorganize Exception Handling?
- Android :: APP Native Code For Android / How To Enable Exception Handling?
- Android :: Sqlite Exception:java.lang.Illegal Argument Exception Column Id Does Not Exist
- Android :: Best Way To Handling XML
- Android :: Try/except Handling For PostMethod?
- Android :: Handcent Handling MMS?
- Android :: Handling Orientation Changes Yourself
- Android :: Handling Of Multitouch?
- Android :: Best Way Of Handling UI Code From Thread?
- Android :: Market Error Handling
- Android :: Long Key Press Handling In 1.5
- Android :: Handling Status Bar Notification
- Android :: Handling Multiple Accounts In App
- Android :: Handling Orientation Changes In AppWidgets
- Android :: Handling Screen Orientation
- Android :: WebView / Handling Orientation Changes
- Android :: Key Event Handling Process
- Android :: Add Event Handling In Each Row In ListView?
- Android :: Any Best Practices For Starting / Handling Activities
- Android :: Handling Expensive Operations In UI Thread
- Android :: Any Application For Handling Large PDF Files?
- Android :: Orientation Change Handling On Widgets
- Android :: EditText Handling While Orientation Change
- Android :: Handling Orientation Changes That Occur In Another Activity
- Android :: ActivityGroup Not Handling Back Key For ListActivity
- Android :: Handling Back Key While Showing A Dialog
- Android : How To Recieve A Rotation Event Handling
- Android :: Odd Behaviour With Launcher's Task Stack Handling
- Android :: Multiple Profile Support - Code Handling
- Android :: Handling Events From One Service For Multiple Activities
- Android :: What's OS Model For Handling Custom Hardware Keys?
- Android :: Handling Java.lang.IndexOutOfBoundsException Has End Before Start Bug
- Android :: Multi Touch Event Handling Is Supported In 1.6 SDK?
- Android :: Make Precise Handling Of Pan And Zoom Finishing?
- Android :: Handling Files Received By Bluetooth Correctly
- Android :: Is Progress Bar Correctly Handling Padding-values
- Android : Way To Create A Custom Call Handling Application?
- Android : Method In ListView Handling Fling Action (up And Down)?
- Android : Bitmap Memory Handling With ImageView.setimage
- Android : Bitmap Memory Handling With ImageView.setimage
Exception Handling
Before you begin to explore Android, you will need to be able to get information from your app and deal with errors.There is LogCat Android tool for exception handling. Once you have your “Hello World” app running , you can start learning about handling errors and getting debug information.
To begin, let’s add a log message to your Hello World application:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("HelloWorld", "Hello LogCat!");
// LogCat message
}
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("HelloWorld", "Hello LogCat!");
// LogCat message
}
After entering the line of code, press Ctrl+Shift+O (organise imports) to import the android.util.Log class. The call to Log.i() creates an info log message. The first parameter is a tag, typically the name of your app, which you can use later to filter out specific log messages. The second parameter is the message to log.
To view the message, you will need to open the LogCat view in Eclipse. Click Window > Show View > Other > Android > LogCat > OK. Once open, you can run the app and watch the view. You will see a lot of messages from various parts of the Android system (OS and apps). Your message will come out in there somewhere! To make it easier to see just your message, click the + sign on the top right of the LogCat view, then fill in the dialog as follows, then click OK: This will create a new tab in your LogCat view titled “HelloWorld” which will only display log messages tagged as “HelloWorld”, and when messages appear in this tab while it is unfocused, it will display a count of unread messages in the tab title.
Log messages can be one of several types: verbose (V), debug (D), info (I), warning (W), or error (E). You can click the corresponding letter in the top bar of the LogCat view to filter by that type of message or above. These are in increasing order of importance, so if you choose to see debug and above, you will also see info, warning, and error messages. Similarly, the Log class has methods for each type of message, e.g. Log.d() for debug.
Right, so you now have an easy way of displaying information from your application without having to worry about adding breakpoints and inspecting variables. Now let’s look at handling errors. To see how an error is naturally handled in Android, let’s create one in our app:
Now let’s look at handling errors. To see how an error is naturally handled in Android, let’s create one in our app:
Log.i("HelloWorld", "Hello LogCat!");
// LogCat message
String test = null;
if (test.equals("hello")) Log.i("HelloWorld", "The test string is hello");
// LogCat message
String test = null;
if (test.equals("hello")) Log.i("HelloWorld", "The test string is hello");
Eclipse will actually warn you about the impending doom, but since we’re too clever for that, let’s go ahead and run our app anyway. Suddenly, we are faced with the infamous “Force close” dialog:
At this point, it will be useful to know that there are two main reasons for a Force Close dialog: an unhandled exception (like this one), or an unresponsive app (perhaps stuck in an infinite loop or using too much CPU for too long). What went wrong? Well, our “HelloWorld” LogCat tab shows nothing, but the “Log” tab shows an error with a stack trace. Helpful, but that might get lost in the sea of log messages, so let’s add some error handling to our app:
Log.i("HelloWorld", "Hello LogCat!");
// LogCat message
try {
String test = null;
if (test.equals("hello")) Log.i("HelloWorld",
"The test string is hello");
} catch (Exception e) {
// handle any errors
Log.e("HelloWorld", "Error in activity", e);
// log the error
// Also let the user know something went wrong
Toast.makeText(
getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
// LogCat message
try {
String test = null;
if (test.equals("hello")) Log.i("HelloWorld",
"The test string is hello");
} catch (Exception e) {
// handle any errors
Log.e("HelloWorld", "Error in activity", e);
// log the error
// Also let the user know something went wrong
Toast.makeText(
getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
The try-catch block of code is standard Java exception handling. We log the error to LogCat in the catch block, and also display a Toast message to the user to show that there was an error. Now, when you run the app, you will see a notification come up about a NullPointerException, alerting you that something went wrong. This prompts you to look at your LogCat output, where the spilled guts of an exception are awaiting your postmortem. Since we have consumed the exception, no Force Close dialog appears. I recommend surrounding the entire code block in the onCreate() method with a try-catch block like this to avoid Force Closes entirely. For more complex applications, there will be several places where you will need to surround your code with try-catch blocks
In summary, Android provides an easy way to log messages to a “console” (which in this case is LogCat). It is important to handle all exceptions thrown by your app (including RuntimeExceptions) to avoid Force Close dialogs. A good way to do this is to surround all executing code with a try-catch block, tag your messages and errors, log them to LogCat, and also present the user with a message about the error (using a Toast). Once you have this base covered, you can begin to code more freely and you will spend a lot less time tracking down errors and Force Closes.
No comments:
Post a Comment