Mobile Phone Handheld Hardware Hardware Rick Rogers John Lombardo O'Reilly Media, Inc. O'Reilly Media Android Application Development, 1st Edition14.3. Exception HandlingWhat if something goes wrong? The code in the call method that
starts the dialer is wrapped in a try/catch block. The
catch statement contains a line of code that logs an
error if the startActivity method throws an exception
of the type ActivityNotFoundException. If a method can
throw an exception that indicates an error, the call to that method should
be in a try/catch block that catches that type of exception. In this case,
we use Android's logging facility to record the error. NOTE We do not catch all exceptions, because unexpected exceptions
indicate failures a program cannot, in general, recover from. Let's make an exception happen. We can do this by removing part of
the data needed to have the startActivity method call work correctly.
Comment out line 22 of the code, as shown: // callIntent.setData(Uri.parse("tel:9785551212"));Now make some changes to breakpoints. Clear the breakpoint on line
21, and set a breakpoint on line 25, where, in the catch clause, the
method of the Log class is called to log the caught
exception. Use the Run Debug command again to start the program. This time you will see execution stop at the new breakpoint you set.
You will also see that an exception has been thrown. The Debug view in
Eclipse shows a stack backtrace, a list of all the
methods called when the exception was thrown. The Variables view shows
that activityException now refers to
the exception that was thrown. Look at the members of the exception to see
the information this exception provides. If you examine the exception that was thrown (you can do this by
hovering your mouse over activityException) you will see that the
explanation for the exception reads "No activity found to handle intent."
That is, in the case of an Intent
object created with Intent.ACTION_CALL
as the argument to the constructor, it also needs the data of the Intent
to be set correctly in order to find an activity to process that
Intent.
 |