Skip to main content

Exceptions

An exception is a condition that is caused by a run-time error in the program. When the Java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws it (i.e., informs us that an error has occurred).

If the object is not caught and handled properly, the interpreter will display an error message and will terminate (stop) the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate (proper) message for taking corrective actions. This task is known as exception handling.

The purpose of exception handling mechanism is to provide a means to detect (find) and report an exceptional circumstance so that appropriate can be taken. The mechanism suggests incorporation (to include) of a separate error handling code that performs the following tasks:

1.      Find the problem (Hit the exception)
2.      Inform that an error has occurred (Throw the exception)
3.      Receive the error information (Catch the exception)
4.      Take corrective actions (Handle the exception)

The error handling code basically consists of two segments, one to detect errors and to throw exceptions and the other to catch the exceptions to take appropriate actions.

When writing programs, we must always be on the lookout for places in the program where an exception could be generated. Some common exceptions that we must watch out for catching are listed below:

·         ArithmeticException – Caused by math errors such as division by zero
·         ArrayIndexOutOfBoundsException – Caused by bad array indexes
·         ArrayStoreException – Caused when a program tries to store the wrong type of data in an array
·         FileNotFoundException – Caused by an attempt to access a nonexistent file
·         IOException – Caused by general I/O failures, such as inability to read from a file
·         NullPointerException – Caused by referencing a null object
·         NumberFormatException – Caused when a conversion between strings and number fails
·         OutOfMemoryException – Caused when there’s not enough memory to allocate a new object.
·         SecurityException – Caused when an applet tries to perform an action not allowed by the browser’s security setting
·         StackOverflowException – Caused when the system runs out of stack space






Java uses a keyword try to preface a block of code that is likely to cause an error condition and throw an exception. A catch block defined by the keyword catch catches the exception thrown by the try block and handles it appropriately. The catch block is added immediately after the try block. The following example illustrates the use of simple try and catch statements:
………………………….
try
{
            statement;       // generates an exception
}
catch (Exception-type e)
{
            statement;       // process the exception
}
……………………………..
……………………………….

The try block can have one or more statements that could generate an exception. If any statement generates an exception, the remaining statements in the block are skipped and execution jumps to the catch blocks that is placed next to the try block.
The catch block too can have one or more statements that are necessary to process the exception. Remember that every try statement should be followed by at least one catch statement; otherwise compilation error will occur.
Note that the catch statement works like a method definition. The catch statement is passed a single parameter, which is reference to the exception object thrown (by the try block). If the catch parameter matches with the type of exception object, then the exception is caught and statements in the catch block will be executed. Otherwise, the exception is not caught and the default exception handler will cause the execution to terminate.
Below program illustrates the use of try and catch blocks to handle an arithmetic exception.
class Error
{
            public static void main (String args[])
            {
                        int a = 10;
                        int b = 5;
                        int c = 5;
                        int x, y;
            try
            {
                        x = a / (b – c);
            }
            catch (ArithmeticException e)
            {
                        System.out.println(“Division by zero”);
            }
            y = a / (b+c);
            System.out.println(“y = “ + y);
            }
}

Output:
Division by zero
y = 1

Note that the program did not stop at the point of exceptional conditional. It catches the error condition, prints the error message, and then continues the execution, as if nothing has happened.


Topic Left: Multiple catch blocks

Resource Used:

1) E Balagurusamy
2) SAMS Teach yourself

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;    ...