Skip to main content

Exception Handling

The present day society is increasing and becoming dependent on computer systems. Whether it is reservation and ticketing for travel by air, train or bus…etc all are controlled by computer systems. So much so that even in sports the decisions of winner or loser in split second finishes are decided by replaying the computer records made during the event. In such an environment it is absolutely necessary that the computer systems (hardware and software) handling these tasks should be highly reliable and should function as expected continuously. However, exceptions do happen either due to failure of a component of hardware system or due to failure of a portion of software/program or due to some unexpected circumstance created during running of the program.
Rarely does program run successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. A mistake might lead to an error causing the program to produce unexpected results. Errors are the wrongs that can make a program go wrong.
An error may produce an incorrect output or may terminate the execution of the program abruptly or even may cause the system to crash. It is therefore important to detect and manage properly all the possible error conditions in the program so that the program will not terminate or crash during execution.
Types of Errors
Errors may broadly be classified into two categories:
·         Compile-time errors
·         Run-time errors
Compile Time Errors
All syntax errors will be detected and displayed by the Java compiler and therefore these errors are known as compile-time errors. Whenever the compiler displays an error, it will not create the .class file. It is therefore necessary that we fix all the errors before we can successfully compile and run the program.
/* This program contains an error */
class Error1
{
            public static void main (String args[])
            {
                        System.out.println(“Hi Amit!”)           // Missing;
            }
}

The Java compiler does a nice job of telling us where the errors are in the program. For example, if we have missed the semicolon at the end of print statement in above Program. The following message will be displayed in the screen:
Error1.java :7:   ’;’ expected
System.out.println (“Hi Amit!”)

We can now go to the appropriate line, correct the error, and recompile the program. Sometimes, a single error may be the source of multiple errors later in the compilation. For example, use of an undeclared variable in a number of places will cause a series of errors of type undefined variable. After we fix such an error, we should recompile the program and look for other errors.
Most of the errors are due to typing mistakes. Typological errors are hard to find. We may have to check the code word by word, or even character by character. The most common problems are:
·         Missing semicolons
·         Missing (or mismatch of) brackets in classes and methods
·         Misspelling of identifiers and keywords
·         Missing double quotes in strings
·         Use of undeclared variables
·         And so on
Other errors we may encounter are related to directory paths. An error such as
            javac : command not found
means that we have not set the path correctly. We must ensure that the path includes the directory where the Java executables are stored.
Runtime Errors
Sometimes, a program may compile successfully creating the .class file but may not run properly. Such programs may turn out wrong results due to wrong logic or may terminate due to errors such as task overflow. Most common run-time errors are:
·         Dividing an integer by zero
·         Accessing an element that is out of the bounds of an array
·         Trying to store a value into an array of an incompatible class or type
·         Passing a parameter that is not in a valid range or value for a method
·         Converting invalid string to a number
·         And many more
When such errors are encountered, Java typically generates an error messages and aborts the program. The program shown below illustrates how a run-time error causes termination of execution of the program.
class Error2
{
public static void main (String args[])
{
            int a = 10;
            int b = 5;
            int c = 5;
            int x = a/(b-c);             // Division by zero
            System.out.println(“x = “ + x);
            int y = a/(b+c);
            System.out.println(“Y = “ + y);
}
}

Here, above program is correct and therefore does not cause any problem during compilation. However, while executing, it displays the following message and stops without executing further statements.

java.lang.ArithmeticException:          / by zero at Error2.main(Error2.java:10)

When Java run-time tries to execute a division by zero, it generates an error condition, which causes the program to stop after displaying an appropriate message.

Note:

This is just an introduction and the later part will be posted by tomorrow. I'd like to request you to finish this article first and then only move for next part. I hope you've enjoyed.

Resources Used:

E Balagurusamy

Compiled By: Chaudhary Amit V.







Comments

Popular posts from this blog

Characteristics of a Good Programming Language

Till now there are many high level languages which are very popular, and there are others, which could not become so popular in-spite of being very powerful. There might be many reasons for the success of a language, but one obvious reason is the characteristics of the language. Several characteristics believed to be important with respect to making a programming language good are briefly discussed below. Simplicity A good programming language must be simple and easy to learn and use. For example, BASIC is liked by many programmers only because of its simplicity. Thus, a good programming language should provide a programmer with a clear, simple and unified set of concepts which can be easily grasped. It is also easy to develop and implement a compiler or an interpreter for a programming language that is simple. However, the power needed for the language should not be sacrificed for simplicity. The overall simplicity of a programming language strongly affects the readability of the pr...

Angular 4 and Firebase Authentication: Setup

If you have come to this article, it means you are keen to learn new technology and that too Firebase. I love Firebase because it provides all basic but important features of any web application. Take for example, authentication, which is cumbersome and risky if not implemented with utmost care. And when we have the integration of Angular and Firebase, it becomes a lot easier for a developer to build such crucial modules in less time with minimal efforts. In this article we will create a simple Angular application using Firebase. I am going ahead with the understanding that you know the benefits of Firebase and have little knowledge about it. There are plenty of posts out on the web if you are behind. Step 1: Install Angular CLI (if not installed). npm install -g angular-cli Step 2: Create new Angular 4 project. By default now angular CLI will create Angular 4 project so you need not fret. ng new firebase-authentication Step 3: Check whether the ne...

Switch-case, simple calculator . . .

11.      Write a program to perform some mathematic functions with the help of “switch-case” statement. #include<stdio.h> #include<conio.h> void main() { int a,b,ans; char c; clrscr(); printf("\ Enter a and b:"); scanf("%d%d",&a,&b); printf("\n Enter operator:"); fflush(stdin); scanf("%c",&c); switch(c) { case'+':ans=a+b;       break; case'-':ans=a-b;       break; case'*':ans=a*b;       break; case'/':ans=a/b;       break; } printf("\n ans %d",ans); getch(); } 12.      Print the Fibonacci series #include<stdio.h> #include<conio.h> void main() { int a=1,b=1,s=3,c,ch; clrscr(); printf("how many steps="); scanf("%d",&ch); printf("%5d%5d",a,b); for(s=3;s<=ch;s++) {       c=a+b;       printf("%5d",c);       a=b;    ...