You are on page 1of 25

CO4- Implement Exception

Handling

Prof: Naresh R. Shende


HOD, Computer Engineering
Shivajirao S. Jondhle Polytechnic
➢ Types of errors
➢ Exceptions
➢ Build-in exceptions
➢ try & catch statement
➢ throw, throws & Finally statement
➢ Creating own exception
Managing errors and Exception

An exception is an abnormal condition that


arises in a code sequence at run time. That
is exception is a run time error.
The errors are classified into two categories:

1. Compile time errors

2. Run time errors


Java compiler detects all syntax errors and displays
it. Suppose a program contains error, the compiler does
not create class file. So it is necessary to fix all
the errors before successful compilation and execution
of program.
class Error 1
{
public static void main (String args[ ])
{
System.out.println (“Hello Java !”)
//; missing
}
}
Error 1. Java :7: ‘;’ Expected
System.out.println (“Hello Java !”)
^
1 error
➢ Missing semicolon
➢ Missing of brackets in classes and method.
➢ Misspelling of identifiers and keywords.
➢ Missing double quotes in strings.
➢ Use of undeclared variables.
➢ Incompatible types of assignment/initialization.
➢ Bad reference to objects.
Commonly occurred runtime errors are:
➢ Dividing an integer by zero.
➢ Accessing an element that is out of the bounds of an array.
➢ Trying to store a value into an array of an incompatible
class or type.
➢ Typing to cast an instance of a class to one of its
subclass.
➢ Passing a parameter that is not in a valid range or value
for a method.
➢ Trying to illegally change the state of a thread.
➢ Attempting to use a negative size for an array.
➢ Using a null object reference.
➢ Converting invalid string to a number.
➢ Accessing a character that is out of bounds of a string.
class Error2
{
public static void main (String args[ ])
{
int a =11;
int b =5;
int c =5;
int x = a/ (b-c); // division by zero
System.out.println (“x=” +x);
int y =a / (b + c);
System.out.println (“y =” + y);
}
}
Java. lang. arithmetic Exception: / by zero
At Error2. main (Error2. Java.10)
Exception Handling is a mechanism which provides a
means to detect errors and throw exceptions, and then
to catch exceptions by taking appropriate actions.

Exception handling mechanism includes a separate error


handling code that performs:
➢ Find the problem (Hit the exception)
➢ Inform that an error has occurred (Throw the exception)
➢ Receives the error information (catch the exception)
➢ Take corrective active (Handle the exception)
➢ ArithmaticException
➢ IOException
➢ NullPointerException
➢ ArrayException
➢ ArrayIndexOutOfBoundsException
➢ FileNotFoundException
➢ NumberFormatException
➢ OutOfMemoryException
➢ SecurityException
➢ StackOverflowException
➢ StringIndexOutOfBoundException
Java exception handling is managed by five keyword:

➢ try
➢ catch
➢ throw
➢ throws
➢ finally
try
{
Statement;
// generates exception or block of code
to monitor for error
}
catch(ExceptionTypeClass Object)
{
Statement; // process the exception
}
class Error3
{
public static void main (String args[ ])
{
int a =10;
int b =5;
int c = 5;
int x, y;
try {
x = a/ (b-c); // Exception here
}
catch(ArithmaticException e)
{
System.out.println (“Division by zero”);
}
y =a/ (b + c);
System.out.println (“y =” + y);
}
}
Output Division by zero
y=1
class NumFormExcp
{
public static void main(String args [ ])
{
String str1 = new String(“text12”);
int num1 = Integer.parseInt(str1);
// convert string to number
System.out.println(num1);
}
}

The output is:


Exception in thread “main”
java.lang.NumberFormatException text12
at java.lang.Integer.parseInt(Compiled Code)
at java.lang.Integer.parseInt(Integer.java.:458)
at NumFormExcp.main(NumFormExcp.java:6)
class NumFormExcp
{
public static void main(String args [ ] )
{
try
{
String str1 = new String(“text12”);
int num1 = Integer.parseInt(str1);
// convert string to number
System.out.println(num1);
}
catch(NumberFormatException e)
{
System.out.println(“Wrong Number”);
}
}
}

The output – Wrong Number


The throw statement is used to explicitly throw
an exception or throw the exceptions by our own,
the throw statement can be used. First a handle
on an instance of throwable must be got into a
catch clause or by creating one using the new
operator.

The general form of a throw statement is given


below.
throw <Throwableinstance>
where <Throwableinstance> is the instance when
the throw has to be executed.
class ThrowDemo
{
public static void main(String args[ ])
{
try
{
throw new NullPointerException( );
}
catch(NullPointerException e)
{
System.out.println(“Invalid reference use”);
}
}
}

Invalid reference use


Whenever is program does not want to handle exceptions
using the try block, it can use the throws clause. The
throws clause is responsible to handle the different
types of exception generated by the program. This
clause contains a list of the various types of
exceptions that are likely to occur in the program.

Syntax:
datatype methodname(parameter_list)throws exception-list
{
//body of method
}
class ThrowsException
{
public static void main(String args[ ]) throws
ArithmaticException
{
System.out.println(“inside main”);
int i=0;
int j=40/i;
System.out.println(“this statement is not printed”);
}
}
The output generated is as follows
inside main
Exception in thread “main”
java.lang.ArithmaticException: / by zero
at ThrowException.main(ThrowException.java:5)
➢ The finally clause is written with the try statement,
rather the try statement must have either the catch or
the finally block, and having both of them within the try
statement is also not a bar.
➢ The benefit of the finally block is that it is definitely
executed after a catch block or before the method quits.
This takes the form as:
try { try
// statements {
} // statement
catch (<exception> obj) }
{ finally
// statement {
} // statement
finally{ }
// statement
}
➢ That is why, while throwing the exceptions
you did not specifically include any package
for exception classes.
➢ Apart from the built-in exception classes
you can define your own exception classes.
➢ This is very useful when you want to define
exception types which are having a behavior
different from the standard exception types,
particularly when you want to do validations
in your application.
In this example the exception class is created and used
in the same java file, but it is possible to create and
store exception types in packages and use them globally.

import java.io.*;
import java.lang.Exception;
class MyException extends Exception
{
MyException(String Message)
{
super(Message);
}
}
class MyExceptionTest
{
public static void main (String args[ ])
{
BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter the number");
int no=Integer.parseInt(br.readLine());
if(no<0)
{
throw new MyException(“Number is negative");
}
else
{
throw new MyException(“Number is positive");
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
➢ Exception means abnormal condition.

➢ Two types of errors Compile Time and Run Time

➢ Runtime Errors are handled using try-catch, throw,


throws and finally block.

➢ Explicitly handled exception through method using


throw keyword.

➢ Java Exception classes(Built in Exception)

➢ User Defined Exception(own exception throw)


handled using throw keyword.

You might also like