You can do this several ways, choose which one fits your scenario best:
- Throw different exceptions based on each error scenario. It is easy to subclass
Exception
and create the distinction this way. - Throw the same exception with a specific error message depending on the error scenario.
An example of case 1:
First define your own exceptions:
public class CannotReadException extends Exception {
// This is a separate class in your project
}
public class CannotWriteException extends Exception {
// This is a separate class in your project
}
Then throw and catch them:
try {
// Test access to the repository:
file = new File(pdfRepository);
if (!file.canRead())
throw new CannotReadException();
if (!file.canWrite())
throw new CannotWriteException();
...
} catch (CannotReadException e) {
// Do stuff for the specific error
} catch (CannotWriteException e) {
// Do stuff for the specific error
}
or, case 2:
try {
// Test access to the repository:
file = new File(pdfRepository);
if (!file.canRead())
throw new SecurityException( "cannot read" );
if (!file.canWrite())
throw new SecurityException( "cannot write" );
...
} catch (SecurityException e) {
// Get to your specific message using e.getMessage();
}