Sample code to handle Exceptions

后端 未结 3 1787
野趣味
野趣味 2021-02-03 12:40

I am new to Android mobile application development. I would like to know, how can I handle exceptions like HttpConnection related exceptions or any other exception

相关标签:
3条回答
  • 2021-02-03 13:08

    There are 2 different kinds of exceptions in Java: Checked and Unchecked. There is a big debate over which one is better to use, both arguments are good.

    Basically a Checked exception is derived from java.lang.Exception and it requires that if you don't specify your method as "throws MyCheckedException" then you must catch and handle the exception within your method.

    // throw the exception
    
    void foo() throws MyCheckedException
    {
        throw new MyCheckedException();
    }
    
    // or handle the exception
    
    void foo()
    {
        try {
           throw new MyCheckedException();
        } catch (MyRuntimeException e) {
            e.printStackTrace();
        }
    }
    

    An Unchecked exception, derived from java.lang.RuntimeException, requires neither that you specify "throws" in your method definition nor that you handle it.

    void foo()
    {
        throw new MyUncheckedException();
    }
    

    The advantage of Checked is that the compiler will warn you when you haven't handled an exception.

    The disadvantage is that you have to declare either a try/catch block or a throws for every Checked exception, and the upper level code can get pretty cumbersome, trying to handle all the different types of Exceptions.

    For this reason, if you're careful you might prefer using Unchecked Exceptions.

    BTW, you can only choose your exception type when you define your own.

    When encountering Exceptions from Java or a 3rd party library, you have to decide how to handle it. e.g. If a 3rd party method throws CheckedException1, then you have to either handle it, or declare the calling method as "throws CheckedException1". If you want to avoid using Checked Exceptions then you can wrap it in an Unchecked Exception and throw that.

    void foo() // no throws declaration
    {
        try {
            thirdPartyObj.thirdPartyMethod(); // this throws CheckedException1
        }
        catch (CheckedException1 e) {
            throw new MyUncheckedException(e); // this will wrap the checked in an unchecked.
        }
    }
    

    Note that you can throw the Unchecked exception without the "throws" declaration. To access the original CheckedException1 from higher up, you can use the .getCause() method of your Unchecked exception.

    void caller()
    {
        try {
            foo();
        } catch (MyUncheckedException e) {
            CheckedException1 ce1 = e.getCause();
            ce1.printStackTrace();
        }
    }
    

    ... but because the exception from foo() is Unchecked, you don't have to handle it or declare "throws".

    Regarding logging, there are different schools of thought on this.

    1. Log it when the exception occurs (low - level)
    2. Log it when it reaches the top (high - level)
    3. Log it when you have enough information to make an appropriate action and/or a log message. (mid - level)

    A good policy I've found is to install an uncaught exception handler which will take care of all uncaught (obviously unchecked) exceptions. This way anything that is missed will be logged and potentially handled before crashing the system.

    public class MyExceptionHandler implements UncaughtExceptionHandler 
    {       
        @Override
        public void uncaughtException(Thread thread, Throwable ex)
        {
            ex.printStackTrace();
        }
    }
    
    // In your high-level code
    Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
    

    and all for Exceptions that can be handled gracefully, catch and handle them in a module where you know enough about the situation to possibly correct the problem and try again.

    0 讨论(0)
  • 2021-02-03 13:12

    You could use the ACRA plugin that offers this functionality or BugSense to gather error reports. Disclaimer: I am a founder at BugSense.

    0 讨论(0)
  • 2021-02-03 13:19

    How you handle exception depends on the exception. If the exception is something that you cannot recover from, and the user needs to know about then you could catch the exception and show it in an AlertDialog:

    try {
      // do something
    } catch (SomeImportantException e) {
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setMessage("User friendly text explaining what went wrong.");
      AlertDialog alert = builder.create();
      alert.show();
    }
    

    For more info on the dialog, see creating dialogs.

    Alternatively, if the exception is something that you can deal with, you can just log information about the exception and move on.

    try {
      // do something
    } catch (SomeLessImportantException e) {
      Log.d(tag, "Failed to do something: " + e.getMessage());
    }
    
    0 讨论(0)
提交回复
热议问题