




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





Introduction: Because errors can happen at any time, and software engineers can commit errors while developing programs we need a mechanism that would help us overcome these errors or so called bugs. The process of removing the bugs is called âdebuggingâ:
Types of Errors in Java Programs: 1- Compile-time errors: These errors are syntactical errors found in the code, due to which a program fails to compile. For example forgetting a semicolon at the end of a java statement or any other syntax errors will lead to compile-time errors. class CompileError{ public static void main(String args[]){ System.out.println(" Hello") System.out.println( This is compile time error) } }
Detecting and correcting compile-time errors is easy as the Java Compiler is displaying the list of errors with the line numbers along with the description. Then the programmer can go back to the program and check the statements line by line and word by word to find the error and correct it.
2- Run-time errors: These errors represent inefficiency of the computer system to execute a particular statement. For example, insufficient memory to store something or inability of the microprocessor to execute some statement come under run-time errors. class RunError{ public static void main(){ System.out.println(" Hello"); System.out.println( âThis is compile time errorâ); } }
As we can see from the above program, the main() method is not complete âStrings args+â is missing. This program will compile but will not execute because the Java Compiler will not detect any error, but the JVM will be looking for âStrings args+â inside the main() method and it will not be found, then we get a run-time error and program will not execute.
3- Logical errors: These errors depict flaws in the logic of the program. The programmer might be using a wrong formula or the design of the program itself is wrong. Logical errors are detected neither by Java Compiler nor by the JVM. The programmer is responsible of them and he/she has to write the correct logic.
An employee has got an increment of 15% of his salary and the programmer wants has developed the program below to calculate the increment of 15% in the salary: class LogicError{ public static void main(String args[]){ double sal = 5000.00; sal = sal * 15/100; System.out.println(" Salary is : " +sal); } }
In the above program, the programmer has calculated the 15% of the salary but not the full salary (base salary + increment). The programmer has done a logic error in the calculation which needs to be written as: sal += sal * 15/100; So this error, only the programmer can find it and correct it, because the compiler and JVM do not know what the programmer wants to do as this task is related to Logic.
Basically, an exception is a runtime error. Can we call a compile-time error as an exception?! No, we canât call compile-time errors exceptions. Compile-time errors come under errors. All exceptions occur only at runtime, but some exceptions are detected at compile time and some others at runtime. The exceptions that are checked at compilation time by the Java Compiler are called âChecked Exceptionsâ, while the exceptions that are checked by the JVM are called âunchecked exceptionsâ.
Unchecked exceptions and errors are considered as unrecoverable and the programmer cannot do anything when they occur. The programmer can write a Java Program with unchecked exceptions and errors and can compile the program. He can see their effect only when he runs the program. So, Java Compiler allows him to write a Java Program without handling the unchecked exceptions and errors. In case of other exceptions (checked), the programmer should either handle them or throw them without handling them. He cannot simply ignore them, as Java Compiler will remind him of them.
Consider this statement: public static void main(String args[]) throws IOException Here, IOException is an example of checked exception. So, we threw it out of main() method without handling it. This is done by âthrowsâ clause written after main() method in the above statement. OF course we can also handle it, but if we are not handling it or even not throwing it, then the Java Compiler will give an error.
The point is that an exception occurs at run-time but in case of checked exceptions, whether you are handling them or not, it is detected at compilation time. So let us define an exception as a runtime error that can be handled by a programmer. This means a programmer can do something to avoid error any harm caused by the rise of an exception. In case of an error, the programmer cannot do anything and hence if error happens, it causes some damage.
All exceptions are declared as classes in Java. Of course, everything in Java is a class. Even errors are also represented by classes. All these classes are descended from a super class called âThrowableâ:
What is Throwable?! Throwable is a class that represents all errors and exceptions which may occur in Java.
What is Super class of all Exceptions?! Exception is super class of all exceptions in Java.
What is the difference between and Exception and an Error?! An exception is an error which can be handled. It means when an exception happens, the programmer can do something to avoid any harm. But an error is an error which cannot be handled, it happens and the programmer cannot do anything about it.
Let us now discuss what happens when there is an exception. Generally, in any program, any files or databases are opened in the beginning of the program. The data from the files is retrieved and processed in the middle of the program. At the end of the program, the files are closed properly, so the data in the files is not corrupted.
In the following program, we will open a file in the beginning, then do some processing and display the output, and finally close the file. To be able to run this program the user must provide the command line arguments otherwise exception will arise. Let us see this situation in the following program. First we will run the program normally, then we will run it without providing command line arguments:
Java.lang
Throwable
Error Exception
Runtime Exception (^) Other Exceptions
When some exception rises inside the try block, the program will not be terminated. When JVM understands that there is an exception, it stores the exception details in an exception stack and then jumps into a âcatchâ block.
Step-2: The programmer should write the âcatchâ block where he should display the exception details to the user. This helps the user to understand that there is some error in the program. The programmer should also display a message regarding what can be done to avoid this error. âcatchâ block looks like the following: catch(Exception ex){ statements; } âexâ is just a reference that is automatically referring to the exception stack where the details of the exception are available, and we can display the exception details by using the following:
Step-3: The programmer should perform clean-up operations like closing the files and terminating the threads. The programmer should write this code in the finally block: finally{ statements; } The specialty of finally block is that the statements inside the âfinallyâ block are executed irrespective of whether there is an exception or not. This ensures that all the opened files are properly closed and all the running threads are properly terminated. So, the data in the files will not be corrupted and the user is at the safe-side.
Performing the above 3 steps is called âException handlingâ. Remember, in exception handling the programmer is not preventing the exception, but instead, the programmer is avoiding any damage that might happen to data. class ExceptionDemo{ public static void main(String args[]){ try{ //open the files: System.out.println("Opening Files ...");
//Do some processing int n = args.length; System.out.println("n = " +n); int a = 45/n; System.out.println("a = " +a);
//Close the files // System.out.println("Closing Files ...");
} catch(ArithmeticException ae){ //Display Exception details System.out.println(ae);
//Display any message to the user System.out.println("Please pass data while running this program"); } finally{ //Close the files System;out.println("Closing Files ..."); } } }
Compile: javac ExceptionDemo.java Run: java ExceptionDemo 10 20 30 40 Output : Opening Files ⌠n = 4 a = 25 Closing Files âŚ
Now, let us execute the same program again: Run: java ExceptionDemo Output : Opening Files ... n = 0 java.lang.ArithmeticException: / by zero Please pass data while running this program Closing Files ...
The first time we executed the program, it was running perfectly. But the second time we run it, we see some exception details, that is because we didnât provide the arguments again. âtry-catchâ is being used, so when there is an exception JVM jumps into catch block. The âfinallyâ block is executed either there is exception or not.
Most of the times there is possibility of more than one exception present in the program. In this case, the programmer should write multiple catch blocks to handle each one of them.
Let us add the code below to the previous program: int b [ ] = { 10 , 20 , 30 , 40}; b[8] = 50; In this program we are creating an array b[ ] with 4 elements. Index of the array represents the element position in the array. So, in our example the index is from 0 to 3 because there are 4 elements. So, there is no index of 8, but we are trying to store the value 50 at index 8 in the second statement. This leads to an exception called ArrayIndexOutOfBoundException. To handle this, we should write another catch block like:
catch(ArrayIndexOutOfBoundsAxception ax){ //display exception details ax.printStackTrace(); //Display a message to the user System.out.println("Please see that the array index is within the range"); }
Write a program which shows how to handle both ArithmeticException and ArrayIndexOutOfBoundsException: class ExceptionDemo{ public static void main(String args[]){ try{ //open the files: System.out.println("Opening Files ...");
//Do some processing int n = args.length; System.out.println("n = " +n); int a = 45/n; System.out.println("a = " +a); int b [] = {10 , 20 , 30 , 40}; b[8] = 50; } catch(ArithmeticException ae){ //Display Exception details
In the above program, the Java Compiler expects the programmer to handle the IOException using try and catch blocks, or else, the programmer should throw the IOException by using âthrowsâ clause, but the programmer is not doing any of them. That is the reason why we get compile time error displayed. We know from the syntax of readLine() method that it is throwing exception, then we must use âthrows IOExceptionâ in our program exactly in the method accept() which is using the method readLine(). And because the method accept() is being called in the main() method, then we must write âthrows IOExceptionâ beside the main() method as shown in this example:
//This example is handling the exception by using "throws" clause: class HandlingException{ private String name; void accept() throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter any Name : "); name = br.readLine(); } void display(){ System.out.println("Name is : " +name); } } class HandlingExceptionDemo{ public static void main(String args[]) throws IOException{ HandlingException yes = new HandlingException() yes.accept(); yes.display(); } } In the above example, we succeeded in throwing the exception by using âthrowsâ clause, instead of handling it by using the try catch blocks.
There is also âthrowâ statement available in Java to throw out an exception explicitly and catch it. Let us see how it can be used. In the following program we are creating an object of NullPointerException class and throwing it out of try block as shown here: Throw new NullPointerException(âException dataâ); In this statement, NullPointerException class object is created and âException dataâ is stored into the object. Then it is thrown using throw statement. Now, we can catch it using catch block as: Catch(NullPointerException npe) { }
Write a program that shows the use of throw clause for throwing the NullPointerException: class ThrowExample{ static void example(){ try{ System.out.println("Inside example() method"); throw new NullPointerException("Exception data"); } catch(NullPointerException npe){ System.out.println("npe"); } } } class ThrowDemo{ public static void main(String args[]){ ThrowExample.example(); } }
In this example, we are using throw clause to throw NullPointerException class object. Then it is caught and its details are displayed in catch block. We used âthrowâ to throw out an exception object and handle it. This activity is useful in software development in the following two ways: