Errors can be divided into two categories:
- Compile time errors
- Run time errors
Compile Time Errors
Compile time errors are also known as design time errors. This can be a syntax error or can be an error in the code design. These kind of errors can easily be caught while writing code in the advanced editors or IDEs that are specially developed for writing Java code.
For example, let's take a simple example for declaring an integer variable.
public static void main(String[] args) {
int num1 = 50
System.out.println("The number is " + num1);
}
Now if I type this code in my IDE or if I compile the above Java code file, then it will immediately show me an error indicator on line #2, i.e., int num1 = 50
Because there is a wrong syntax in that line. I have not ended the statement with a semi colon ";
". So I will get a compilation error when I try to compile the above code. And the developer can easily go to line#2 and fix the error.
Let's take another example from File handling.
public static void main(String[] args) {
String fileName=null;
if(args!=null && args.length>0){
fileName=args[0];
}
File file = new File (fileName);
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(file) );
writer.write( "Hello World" );
writer.close();
}
Now the above code looks good without any syntax error. But again, Java will not be able to compile the above code. Though there is no syntax error in the code, there are some exceptions in the code structure. Just think if the file you are looking for in the program doesn't exist in the given location.
If you try to compile this code, it will give you few Exceptions saying that FileNotFoundException
and IOException
should be caught or handled.
Run Time Errors
Runtime errors are known as logical errors which cannot be caught in the editors or while compiling the source code. Java will able to compile the source code successfully and generate the binary .class files, because everything looks good to the compiler both syntactically and structurally.
These errors occurred in run time when the application is actually executed by the end user.
The runtime errors normally occurred due to some fault in your code logic or due to invalid inputs provided to the application, which the application is not expected or designed to receive. These errors can break or crash your application logic in run time.
For example, let's take an example of a simple arithmetic operation.
public static void main(String[] args) {
if(args!=null && args.length>1){
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int result = num1/num2;
System.out.println(num1 + "/" + num2 + " = " + result);
}
}
The above program accepts two numbers as arguments and divides the 1st number by the 2nd number.
Java will compile the above source code without any compilation error and generate the .class file.
Let's consider a case when the user runs the application with passing 0
as the 2nd argument.
Then, it will give the user a Run time error on "divide by zero", as anything divide by zero is undefined. It will return the following arithmetic exception at the line # where the integer type variable is divided by zero, i.e., int result = num1/num2;
Exception in thread "main" java.lang.ArithmeticException:
So the developers should always take precautions in their code by handling the Exceptions that may occur during run time. This will prevent their program from crashing and the application will run flawless even if some part of the application program fails to execute.
Handling Exceptions
Exceptions can be handled by using 'try
-catch
' block. Try
block contains the code where you suspect that there might be exceptions. The catch
block contains the alternatives for the exception. If any exception occurs in the try
block, then the control jumps to the catch
block where you can output some custom message to the users or do some alternatives.
Let's see how we can handle the run time exception in the first example, i.e., "divide by zero" by using try
-catch
block.
public static void main(String[] args) {
if(args!=null && args.length>1){
try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int result = num1/num2;
System.out.println("The result is " + result);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Again, there can be another Exception that occurred in the above code such as if the user passes two string
s instead of two numbers.
So it is better if you can be specific on your Exceptions.
public static void main(String[] args) {
if(args!=null && args.length>1){
try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int result = num1/num2;
System.out.println(num1 + "/" + num2 + " = " + result);
}
catch (NumberFormatException e) {
System.out.println("Enter numeric values only.");
}
catch (ArithmeticException e) {
System.out.println("Undefined result.");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Let's see how we can handle the compile time exception in the second example, i.e., "File handling example" by using try
-catch
block.
public static void main(String[] args) {
File file = new File ("MyTextFile.txt");
try {
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(file) );
writer.write( "Hello World" );
writer.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
}
}
Java 7 has made it much easier with writing less code.
This will automatically close the stream at the end of the try
block, you don't have to write a step to close the file.
try ( OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file)) ) {
writer.write( "Hello World" );
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
}
These are some code examples on handling compilation and run time errors in Java programming. Hope this helps you in getting started with Exception handling in Java.