Docsity

INFORMATIQUE INDUSTRIAL, High school final essays of Computer science

Toggle sidebar
bg1
E X C E P T I O N H A N D L I N G
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.
pf3
pf4
pf5
pf8

Partial preview of the text

Download INFORMATIQUE INDUSTRIAL and more High school final essays Computer science in PDF only on Docsity!

E X C E P T I O N H A N D L I N G

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.

Exceptions:

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:

  • Print() or println() methods: System.out.println(ex);
  • printStackTrace() method of Throwable class which fetches the exception details from the exception stack and displays them.

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.

Handling Multiple Exceptions:

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.

throw Clause:

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:

  • “throw” clause is used in software testing to test whether a program is handling all the exceptions as claimed by the programmer. Now, let us see how this is done: Suppose a programmer has written a program to handle some 5 exceptions properly. Now, the software tester has to test and certify whether the program is handling all the 5 exceptions as said by the programmer or not. For this, the tester should plan the input data such if he provides that input, the said exception will occur. Causing the exceptions intentionally like this will be at times very difficult. In this case, the tester can take the help of “throw” clause. Suppose the tester wants to test whether IOException is handled by the program or not, he can introduce a statement in the source code as: Throw new IOException(“My IOException “); Then he will compile and run the program. Then the above statement will raise the IOException and the rest of the program should handle it. How the program handles that will be noted down by the tester for feedback to the programmer. That is how the “throw” clause will help the tester to test a program for exceptions.
  • “throw” clause can be used to throw our own exceptions also. Just like the exceptions available in Java, we can also create our own exceptions which are called “user-defined exceptions”. We need the throw clause to throw these user defined exceptions.