I am new in Android environment and I have started writing some code to execute some queries on a database. When I have to handle exceptions I don't know what the appropriate way is to do it - out of Android I used to use throws
declaration on methods but it seems that throws
isn't allowed in android? Just try-catch
?
I say this because eclipse doesn't suggest me adding throws
declaration like when I am out of Android environment, I guess that it is related to extends Activity
.
So what is the appropriate way to handle exceptions in android? Surrounding every sentence with try-catch
makes my code look terrible and that's not really what I want to do.
So you use a “try catch” block. Try essentially asks Java to try and do something. If the operation is successful, then the program will continue running as normal. If it is unsuccessful, then you will have the option to reroute your code while also making a note of the exception. This happens in the “catch” block.
How Exceptions Work in JVM and Android. In Java, all exception and error types are subclasses of Throwable. The Throwable class changes the execution flow of JVM apps by throwing exceptions and deciding how to recover from an error. Adding an exception to a code changes its execution flow.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken textview to show exception message.
If the method you are using already throws an exception, you may want to just re-throw the exception as the new type:
public void someMethod() throws IOException {
try {
// Do database operation
} catch (MyException e){
throw new IOException(e.toString());
}
}
// Or, if there is no exception, use an unchecked exception:
public void otherMethod() {
try {
// DB operation
} catch (MyException e){
throw new RuntimeException(e);
}
}
The other option is to make MyException
extend RuntimeException
. Then the compiler won't force you to catch it or add it to the method signature. RuntimeExceptions are known as unchecked exceptions meaning you don't have to check for them occurring by way of a try/catch. Examples of these are NullPointer
and ArrayOutOfBounds
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With