Exception Handling

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 16

Exception handling

• When we write a program, we may make some common


mistakes while typing the program. A mistake may cause
the program to produce unexpected result. Errors are the
wrongs that may cause the program to go wrong.

• Due to errors, the program may not work properly. It is


therefore important to detect and manage properly all
the possible errors in the program so that the program
will not terminate or crash during execution.
• Errors are broadly classified into two types:
– Compile time errors(syntax errors)
– Run time errors(logical errors)
The most common types of compile time errors are:
1. Missing semicolons
2. Missing brackets
3. Wrongly typed identifier and keywords
4. Missing double quotes in string
5. Use of undeclared variables.
6. Incompatible assignments/initializations
7. Using = instead of ==
• Sometimes it happens that our program compiles successfully

but when we run it gives us strange result. This may due to

the wrong logic of the program and hence our program

produces unexpected results. Th most common run time

errors are:
1. Divide by zero

2. Accessing an element beyond index in array.

3. The file we need, don’t exist.

4. Storing wrong type of values in array and many more…


Exception
• An exception is a condition that is caused by run time error.
When java interpreter encounters a run time error viz divide
by zero, it creates a exception object and trows it( i.e. inform
about the error)
• If we have written the code to catch the exception and handle
it properly, then our program will keep running, otherwise the
whole program will collapse.
• So, the process of catching the exception thrown by the error
condition and then display an appropriate message for the
same is called ‘Exception handling’.
• The purpose of exception handling is to provide a means to
detect and report an “exceptional circumstance” so that
appropriate action can be taken. The mechanism supports
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 information(Catch the exception)


4. Take corrective actions(handle the exception)
• The error handling code basically consists of
two segments, one to detect the errors and
throw exception and the other to catch
exception and to take appropriate action.
• When writing a program, we must always look
out for places in the program where an
exception could be generated.
Some common exceptions
• ArithmeticException: It is thrown when an exceptional condition has occurred in an

arithmetic operation.

• ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been

accessed with an illegal index. The index is either negative or greater than or equal

to the size of the array.

• ClassNotFoundException: This Exception is raised when we try to access a class

whose definition is not found

• FileNotFoundException: This Exception is raised when a file is not accessible or does

not open.

• IOException: It is thrown when an input-output operation failed or interrupted

• InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some


• NoSuchFieldException: It is thrown when a class does not contain the field (or

variable) specified

• NoSuchMethodException: It is thrown when accessing a method that is not found.

• NullPointerException: This exception is raised when referring to the members of a

null object. Null represents nothing

• NumberFormatException: This exception is raised when a method could not

convert a string into a numeric format.

• StringIndexOutOfBoundsException: It is thrown by String class methods to

indicate that an index is either negative or greater than the size of the string

• IllegalArgumentException : This exception will throw the error or error statement

when the method receives an argument which is not accurately fit to the given

relation or condition. It comes under the unchecked exception.


Types of exception
Exceptions in java can be categorized into two types:

1) Checked Exception: These exceptions are explicitly

handled in the code itself with the help of try catch block.

They are extended from java.lang.Exception class.

2) Unchecked Exception: These exceptions are not

essentially handled in the program code; instead the JVM

handles such exceptions. They are extended from

java.lang.RuntimeException class.
Syntax of exception handling code
• Java try and catch
• The try statement allows you to define a block of code to be tested for errors
while it is being executed.
• The catch statement allows you to define a block of code to be executed, if an
error occurs in the try block.
• The try and catch keywords come in pairs:
• Syntax
• try
• {
• // Block of code to try
• }
• catch(Exception e)
• {
• // Block of code to handle errors
• }
• // Java program to demonstrate ArithmeticException
• class ArithmeticException_Demo
• {
• public static void main(String args[])
• {
• try {
• int a = 30, b = 0, c = 5;
• int c = a/b; // cannot divide by zero
• System.out.println ("Result = " + c);
• }
• catch(ArithmeticException e) {
• System.out.println ("Can't divide a number by 0");
• }
• int y = a / c;
• System.out.println (“y = “ + y);
• }
• }
• //Java program to demonstrate NullPointerException
• class NullPointer_Demo
• {
• public static void main(String args[])
• {
• try {
• String a = null; //null value
• System.out.println(a.charAt(0));
• }
• catch(NullPointerException e)
• {
• System.out.println("Null Pointer Exception..");
• }
• }
• }
• public class Demo1
• {
• public static void main(String[ ] args)
• {
• try
• {
• int[] myNumbers = {1, 2, 3};
• System.out.println(myNumbers[10]);
• }
• catch (ArrayIndexOutOfBoundsException e)
• {
• System.out.println(“Array is out of bound.");
• }
• }
• }
Multiple catch statements
• public class MultipleCatchBlock1
• {
• public static void main(String[] args) {
• int a[ ] = { 5 , 10 } , b = 5;
• try{
• int x = a[2] / b - a[1];
• }
• catch(ArithmeticException e)
• {
• System.out.println(“Division by zero");
• }
Multiple catch statements
• catch(ArrayIndexOutOfBoundsException e)
• {
• System.out.println(“Array index error");
• }
catch(ArrayStoreException e)
• {
• System.out.println(“Wrong data type");
• }
• int y = a[1] / a[0];
• System.out.println(“y= “ + y);
• }
• }
Using Finally statement
• The finally statement lets you execute code, after try...catch,
regardless of the result:
• public class Demo2
• {
• public static void main(String[ ] args)
• {
• try {
• int[] myNumbers = {1, 2, 3};
• System.out.println(myNumbers[10]);
• }
• catch (ArrayIndexOutOfBoundsException e) {
• System.out.println(“Array is out of bound.");
• }
• finally {
• System.out.println("The 'try catch' is finished.");
• }
• }
• }

You might also like