I am wondering would it make sense to use Java's try and catch statements to request user app permissions, if we get SecurityException?
Rough example would be:
int hasReadExternalStoragePermission = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (hasReadExternalStoragePermission != PackageManager.PERMISSION_GRANTED) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(
MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// inform user
}
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_READ_EXTERNAL_STORAGE_OPEN_PROJECT);
return;
}
myFunction();
versus
try {
myFunction();
} catch (SecurityException) {
ActivityCompat.requestPermissions(
MainActivity.this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE);
return;
}
Pros and cons for both approaches?
Some thoughts on unchecked exceptions: https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Recalling that SecurityException
is a runtime exception, I emphasize this part:
Runtime exceptions represent problems that are the result of a programming problem, (...)
So I understand that requesting permission after a thrown SecurityException
means that the program has a problem of not checking whether the app has some specific permission before calling an operation. I particularly avoid developing problematic programs.
Nonetheless, both codes will work the same.