Exception handling
Lecture - 30
Did you notice the
gaps between two
rail tracks???
In
If summer,
there is no
duegapto
Why??? Thermal
heat,
between
iron the
will
Expansion
tracks,expand
it will bend
Accidents!!!
Result???
So, We have to rectify That’s why we are
that accidents having gaps between
the rail tracks
An exception is
handled here
Similarly in Java
How to handle
also we may get
it?????
problems
Exception
Abnormal condition
or not coming under
any rule
Exception in Java
• In Java, an exception is an event that disrupts the normal flow of the
program.
• It is an object which is thrown at runtime.
Exception Handling in Java
• Exception Handling is a mechanism to handle runtime errors
• Runtime errors
• ClassNotFoundException,
• IOException,
• SQLException,
• RemoteException, etc.
Compile time error run time error
What is the difference???
public class Test
{
public static void main(String a[])
{
Compile time error
System.out.println("Hello")
}
}
Error:
Output : ?????
C:\Sample>Javac Test.java
Syntax Errors Test.java:3: error: ';' expected
System.out.println("Hello")
public class Test
{
public static void main(String a[])
{
Run time error int arr[]=new int[5];
arr[10]=20;
}
}
Error:
Output
Exception in thread : ?????
"main"
logical Errors java.lang.ArrayIndexOutOfBoundsException: 10
at Test.main(Test.java:6)
Syntax Errors Errors
logical Errors Exceptions
We have to clear the
Errors error
Can not
by following
be handled
the
syntax
Exceptions Can be handled
Types of Java Exceptions
Exceptions
Checked Unchecked
Exceptions Exceptions
Checked Exception
• The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions
• Example
• IOException,
• SQLException etc.
• Checked exceptions are checked at compile-time.
Unchecked Exception
• The classes which inherit RuntimeException are known as unchecked
exceptions
• Example
• ArithmeticException,
• NullPointerException,
• ArrayIndexOutOfBoundsException etc.
• Unchecked exceptions are not checked at compile-time, but they are
checked at runtime.
Common Scenarios of Java Exceptions
ArithmeticException
int a=50/0;
Common Scenarios of Java Exceptions
NullPointerException
String s=null;
System.out.println(s.length());
Common Scenarios of Java Exceptions
NumberFormatException
String s="abc";
int i=Integer.parseInt(s);
Common Scenarios of Java Exceptions
ArrayIndexOutOfBoundsException
int a[]=new int[5];
a[10]=50;
Java Exception Keywords
try
catch
finally
throw
throws
try
The "try" keyword is used to specify a block
where we should place exception code
The try block must be followed by either
catch or finally
catch
The "catch" block is used to handle the
exception.
It must be preceded by try block which
means we can't use catch block alone
It can be followed by finally block later
finally
The "finally" block is used to execute the
important code of the program
It is executed when an exception is handled
or not.
throw
The "throw" keyword is used to throw an
exception
throws
The "throws" keyword is used to declare
exceptions, it doesn't throw an exception
It specifies that there may occur an
exception in the method.
Java Exception Handling Example
import java.util.*; catch(ArithmeticException e)
public class Test {
{ System.out.println(e);
public static void main(String args[]) }
{ System.out.print(i+" ");
Scanner s=new Scanner(System.in);
int n=s.nextInt(); }
catch block to catch
for(int i=0; i<=n; i++) }
the exception if
{ }
occurred
try
{
Calculation in try Output:
int data=100/i; java.lang.ArithmeticException: / by zero
block 0 1 2 3 4 5 6 7 8 9 10
}
Program with multiple catch
import java.util.*; catch(ArithmeticException e)
public class Test {
{ System.out.println(e);
public static void main(String args[]) }
{ catch(ArrayIndexOutOfBoundsException e)
Scanner s=new Scanner(System.in); {
int n=s.nextInt(); System.out.println(e);
int arr[]=new int[3]; }
for(int i=0;i<=n;i++) }
{ }
try } Output:
{ java.lang.ArithmeticException: / by zero
int data=100/i; java.lang.ArrayIndexOutOfBoundsException: 3
arr[i]=data;
java.lang.ArrayIndexOutOfBoundsException: 4
java.lang.ArrayIndexOutOfBoundsException: 5
}
Java finally block
• Java finally block is always executed whether exception is handled or
not.
• Java finally block follows try or catch block.
Java finally block
Java finally block- example
import java.util.*; count++;
public class Test System.out.println(e);
{ }
public static void main(String args[]) finally
{ {
Scanner s=new Scanner(System.in); if(i==n)
double data; {
int count=0, n=s.nextInt(); if(count==0 )
for(int i=0;i<=n;i++) System.out.println("No exception ");
{ else
try System.out.println(count +" exception handled");
{ }
data=100/i; }
System.out.println(data+ " "); }
} }
catch(ArithmeticException e) }
{
Output:
java.lang.ArithmeticException: / by zero
100.0
50.0
33.0
25.0
20.0
16.0
14.0
12.0
11.0
10.0
1 exception handled
Java throw keyword
throw
used to explicitly throw an
exception
can throw either checked or
unchecked exception
Java throw block- example
import java.util.*;
public class Test
static void validate(int age)
if(age<18)
throw new ArithmeticException("Under Age");
else
System.out.println("welcome to vote");
}
Output:
public static void main(String args[])
Exception in thread "main"
{
java.lang.ArithmeticException: Under Age
Scanner s=new Scanner(System.in);
at Test.validate(Test.java:7)
int n=s.nextInt();
at Test.main(Test.java:15)
validate(n);
Command exited with non-zero status 1
}
}
Till now we discussed about
What if a checked
how to deal with unchecked throws
exception occurs???
exceptions
throws keyword
throws
used to declare an exception
It gives an information to the
programmer that there may
occur an exception
throws keyword
Syntax
return_type method_name() throws exception_class_name
{
//method code
}
throws keyword
Example
void method()throws IOException
{
//method code
}
throws keyword example
import java.io.*; M m=new M();
class M m.method();
{ }
void method()throws IOException }
{
throw new IOException("device error");
public class Test Output:
{ Exception in thread "main"
java.io.IOException:device error
public static void main(String args[])throws
IOException
at M.method(Test.java:6)
at Test.main(Test.java:14)
{
Command exited with non-zero status 1
Difference between throw and throws