Simple Java Exception Handling Tips
Exceptions are errors that occur in runtime , that is , when the application is running.
A careful developer should estimate and care about possible runtime errors.
Let us give an example :
String s = args[0];
int i = Integer.parseInt(s);
this piece of code can cause some exceptions. For example args is an array of string. We want to read the first element of this array. What happens if args is null ? What happens if args is empty ?
so we need to ensure that the array is not null and not empty.
But there is still a possible cause of exception. We here assume that if s is not null than s contains an integer value that can be parsed without an error. But assumptions always cause exceptions. String s can be a "hello world" string and parseInt fails with this value.
so we need to rewrite our code :
as an alternative to try/catch blocks we can declare our methods as it throws exception , for example :
A careful developer should estimate and care about possible runtime errors.
Let us give an example :
String s = args[0];
int i = Integer.parseInt(s);
this piece of code can cause some exceptions. For example args is an array of string. We want to read the first element of this array. What happens if args is null ? What happens if args is empty ?
so we need to ensure that the array is not null and not empty.
- // check the array is not null or empty
- if (args != null && args.length > 0)
- s = args[0];
- int i = 0;
- if (s != null) // if s is not null we can parse
- else { // s is null , so show an error message and exit
- "Invalid argument , should be a valid integer value" );
- }
But there is still a possible cause of exception. We here assume that if s is not null than s contains an integer value that can be parsed without an error. But assumptions always cause exceptions. String s can be a "hello world" string and parseInt fails with this value.
so we need to rewrite our code :
- if ( args != null && args.length > 0 ) //check the argument array is null or empty
- s = args[0];
- int i = 0 ;
- if ( s != null ) { //if s is not null we can try to parse
- try {
- e.printStackTrace(); //dump the error
- }
- }
- else { // s is null , so show an error message and exit
- }
as an alternative to try/catch blocks we can declare our methods as it throws exception , for example :
Comments