0% found this document useful (0 votes)
13 views

ExceptionHandeling (1)

important notes

Uploaded by

palaknegi.ddn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

ExceptionHandeling (1)

important notes

Uploaded by

palaknegi.ddn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Exception

Exception is an event that arises during the execution of the program, and it
terminates the program abnormally. It then displays system generated error
message.

Exception Handling
Exception handling is the mechanism to handle the abnormal termination of the
program.
For example :ClassNotFoundException, NumberFormatException,
NullPointerException etc.

Need for Exception Handling


A program rarely executes without any errors for the first time. Users may run
applications in unexpected ways. A program should be able to handle these
abnormal situations.
 Exception handling allows executing the code without making any changes to
the original code.
 It separates the error handling code from regular code.

Exception Hierarchy in Java

Difference between error and exception

Error Exception

It cannot be caught. It can be handled by try and catch block.

Errors are by default unchecked type. Exception can be either checked or unchecked
type.

It is defined in java.lang.Error package. It is defined in java.lang.Exception package.

Errors are generally caused by environment Exceptions are generally caused by application
in which application is running. itself.

Example: StackOverflowError, Example: SQLException, IOException,


OutOfMemoryError etc. ClassCastException,
ArrayOutOfBoundException
Types of Exceptions
Java has two types of exceptions.
1. Checked exception (compiled time exception)
2. Unchecked exception (runtime exception)

1. Checked Exceptions
 Checked exceptions are also known as compiled time exception, because such
exceptions occur at compile time.
 Java compiler checks if the program contains the checked exception handler or
not at the time of compilation.
 All these exceptions are subclass of exception class.
 Developer has overall control to handle them.
For example: SQLException, IOException, ClassNotFoundException etc.

Example : Sample program for checked exception

import java.io.File;
import java.io.PrintWriter;
public class Checked_Demo
{
public static void main(String args[])
{
File file=new File("E://abc.txt");
PrintWriter pw = new PrintWriter("file");
}
}

Output:
error: FileNotFoundException

2. Unchecked Exceptions
 Unchecked exceptions are also known as runtime exception.
 These include logic errors or improper use of API.
For example: ArrayIndexOutOfBoundException, NullPointerException,
ArithmeticException.

Example : Sample program for unchecked exception


class Uncheked_Demo
{
public static void main(String args[])
{
int a = 10;
int b = 0;
int c = a/b;
System.out.println(c);
}
}

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero

There are five keywords used in Java for exception handling. They are:
i. try
ii. catch
iii. throw
iv. throws
v. finally

The try block


The try block contains the code that might throw an exception. The try block
contains at least one catch block or finally block.

The catch block


A catch block must be declared after try block. It contains the error handling
code. A catch block executes if an exception generates in corresponding try
block.

Syntax

try
{
//code that cause exception;
}
catch(Exception_type e)
{
//exception handling code
}

Example : An examples to uses try and catch block in java

class TryCatchDemo
{
public static void main(String args[])
{
int a = 30, b = 3, c = 3;
int result1, result2;
try
{
result1 = a / (b - c);
}
catch(ArithmeticException ae)
{
System.out.println("Divided by zero: "+ae);
}
result2 = a / (b + c);
System.out.println("Result2 = "+result2);
}
}

Output :
Divided by zero: java.lang.ArithmeticException: / by zero
Result2 = 5

Example : A program to illustrate the uses of try and catch


block

class ExceptionDemo
{
public static void main(String args[])
{
try
{
int arr[] = new int[5];
arr[2] = 5;
System.out.println("Access element two: " + arr[2]);
arr[7] = 10;
System.out.println("Access element seven: "+ arr[7]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown:" + e);
}
System.out.println("End of the block");
}
}

Output :
Access element two: 5
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 7
End of the block

Multiple catch blocks


If more than one exception is generated by the program then it uses multiple
catch blocks. A single try block can contain multiple catch blocks.

Syntax

try
{
// code which generate exception
}
catch(Exception_type1 e1)
{
//exception handling code
}
catch(Exception_type2 e2)
{
//exception handling code
}

Example : A program illustrating multiple catch block using


command line argument

public class MultipleCatch


{
public static void main(String args[])
{
try
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = a / b;
System.out.println("Result = "+c);
}
catch(ArithmeticException ae)
{
System.out.println("Enter second value except zero.");
}
catch (ArrayIndexOutOfBoundsException ai)
{
System.out.println("Enter at least two numbers.");
}
catch(NumberFormatException npe)
{
System.out.println("Enter only numeric value.");
}
}
}

Output:
10 5
Result = 2

10 0
Enter second value except zero.

5
Enter at least two numbers.

10 a
Enter only numeric value.

The finally block

 The code present in finally block will always be executed even if try block
generates some exception.
 Finally block must be followed by try or catch block.
 It is used to execute some important code.
 Finally block executes after try and catch block.
Syntax

try
{
// code
}
catch(Exception_type1)
{
// catch block1
}
Catch(Exception_type2)
{
//catch block 2
}
finally
{
//finally block
//always execute
}

Example : A program to implement finally block


class FinallyTest
{
public static void main(String args[])
{
int arr[] = new int[5];
try
{
arr[7] = 10;
System.out.println("Seventh element value: " + arr[7]);
}
catch(ArrayIndexOutOfBoundsException ai)
{
System.out.println("Exception thrown : " + ai);
}
finally
{
arr[0] = 5;
System.out.println("First element value: " +arr[0]);
System.out.println("The finally statement is executed");
}
}
}

Output:
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 7
First element value: 5
The finally statement is executed

The throw keyword in Java

 The throw keyword in Java is used to explicitly throw our own exception.
 It can be used for both checked and unchecked exception.
Syntax:
throw new Throwable_subclass;

Example : A program to illustrate throw keyword in java


public class ThrowTest
{
static void test()
{
try
{
throw new ArithmeticException("Not valid ");
}
catch(ArithmeticException ae)
{
System.out.println("Inside test() ");
throw ae;
}
}
public static void main(String args[])
{
try
{
test();
}
catch( ArithmeticException ae)
{
System.out.println("Inside main(): "+ae);
}
}
}

Output:
Inside test()
Inside main(): java.lang.ArithmeticException: Not valid

The throws keyword in Java

 The throws keyword is generally used for handling checked exception.


 When you do not want to handle a program by try and catch block, it can be
handled by throws.
 Without handling checked exceptions program can never be compiled.
 The throws keyword is always added after the method signature.
Example : A program to illustrate uses of throws keyword

public class ThrowsDemo


{
static void throwMethod1() throws NullPointerException
{
System.out.println ("Inside throwMethod1");
throw new NullPointerException ("Throws_Demo1");
}
static void throwMethod2() throws ArithmeticException
{
System.out.println("Inside throwsMethod2");
throw new ArithmeticException("Throws_Demo2");
}
public static void main(String args[])
{
try
{
throwMethod1();
}
catch (NullPointerException exp)
{
System.out.println ("Exception is: " +exp);
}
try
{
throwMethod2();
}
catch(ArithmeticException ae)
{
System.out.println("Exception is: "+ae);
}
}
}
Output:
Inside throwMethod1
Exception is: java.lang.NullPointerException: Throws_Demo1
Inside throwsMethod2
Exception is: java.lang.ArithmeticException: Throws_Demo2

Difference between throw and throws keyword in Java

Throw Throws

It is used to throw own exception. It is used when program does not handle exception
via try block.

It handles explicitly thrown exceptions. It handles all exceptions generated by program.

Cannot throw multiple exceptions. Declare multiple exception e.g.


public void method() throws, IOException,
SQLException.

It is used within the method. It is used within method signature.

You might also like