Lecture-27 Java SE (Exception Handling-1)
Lecture-27 Java SE (Exception Handling-1)
Lecture-27
Today’s Agenda
01 Exception Handling
04 Exception hierarchy
Exception Handling
• Exception in programming languages like java means run time errors i.e. errors
which appear during execution of a program.
• It might be due to user’s wrong input or any logical fallacy of the program.
• But before understanding how to handle exception, first let us understand what java
does when an exception occurs.
2. It defines the reason for exception but is highly technical and is not friendly to an
user.
2. catch
3. throw
4. throws
5. finally
try and catch
• Syntax:-
try Those lines on which an exception may occur are written
{ in the try block.
--- As soon as an exception occurs, java leaves the try
--- block and moves towards the catch block.
}
catch(<Exception class name> <object reference>)
{ Object reference points to that object which is sent
--- by the try block after an exception occurs.
--- The class should be similar to the exception which
} has occurred. Example, ArithmeticException
class.
try and catch
• There cannot be any other line between a try and a catch block, they should be
continuous.
• All exceptions are pre defined classes in java. If no catch block matches the exception
object then java shows its default behavior.
Error Exception
• They rule is that, a parent class of exception hierarchy cannot come before its
child class.
• This is because a reference of parent class can easily point to the child class
object and hence, the child class catch block will never run.
Example
try try
{ {
---- ----
---- ----
} }
catch(IOException e) catch(FileNotFoundException f)
{ {
---- ----
---- ----
} }
catch(FileNotFoundException f) catch(IOException e)
{ {
---- ----
---- ----
} }
Exercise
• WAP to accept 2 integers from the user and display the result of their division and
sum. Your program should behave in the following way –
1. If both the inputs are integers and are valid then the program should display the
result of their division and sum.
2. If denominator is then program should display relevant error message but should
display the sum.
3. If input value is not an integer then the program should display relevant message
and neither division nor sum should be displayed.
Solution
import java.util.Scanner;
class DivideAndSum
{
public static void main(String [ ] args)
{
Scanner kb=new Scanner(System.in);
int a=0,b=0;
try
{
System.out.println(“Enter two numbers”);
a=kb.nextInt();
b=kb.nextInt();
int c=a/b;
System.out.println(“Division is ”+c);
}
Exercise
catch(ArithmeticException e)
{
System.out.println(“Denominator should not be 0”);
}
catch(InputMismatchException ex)
{
System.out.println(“Please enter integers only”);
System.exit(0);
}
int d=a+b;
System.out.println(“Sum is ”+d);
}
}
Thank you