SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
FACULTY OF SCIENCE AND HUMANITIES
DEPARTMENT OF COMPUTER SCIENCE
OBJECT-ORIENTED PROGRAMMING USING JAVA - UCS24202J
UNIT - III
Exception Handling:
Exception is an abnormal condition.
An exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
Java provides five keywords that are used to handle the exception. The following table describes
each.
Example Program:
public class JavaExceptionExample
{
public static void main(String args[])
{
try
{
int data=100/0;
System.out.println("This line will never be printed”);
}
catch(ArithmeticException e) {
System.out.println(e);
}
System.out.println("After Catch”);
}
}
OUTPUT:
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch
block. The error object created in the try block is throwed to the respective catch block and the
error details are printed in the output. Once an error occurs we can’t return back to the rest of the
statements in the try block. The code which is next to the catch block will be executed.
Using multiple catch clauses:
A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler. So, if you have to perform different tasks at the occurrence of different
exceptions, use java multi-catch block.
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
import java.util.Scanner;
public class MultipleCatchBlock {
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
System.out.println(“ Enter the Divisor number:”);
int b=s.nextInt();
try{
int a[]=new int[5];
a[5]=30/b;
System.out.println(a[10]);
}
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
System.out.println("rest of the code");
} }
Output:
Working with Finally,
Java finally block is a block used to execute important code such as closing the connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it contains
all the necessary statements that need to be printed regardless of the exception occurs or not. The
finally block follows the try-catch block.
public class TestFinallyBlock{
public static void main(String args[]){
try {
System.out.println("Inside try block");
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
OUTPUT:
throw:
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. These exceptions may be related to user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used
to throw a custom exception.
For example, we can throw ArithmeticException if we divide a number by another number.
Here, we just need to set the condition and throw exception using throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance
In this example, we have created the validate method that takes integer value as a parameter. If the
age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome
to vote.
public class TestThrow {
public static void validate(int age) {
if(age<18) {
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
OUTPUT:
throws
if there is a chance of raising an exception then the compiler always warns us about it and
compulsorily we should handle that checked exception, Otherwise, we will get compile time error
saying unreported exception XXX must be caught or declared to be thrown. To prevent this
compile time error we can handle the exception in two ways:
1. By using try catch
2. By using the throws keyword
class ThrowsExecp {
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try {
fun();
}
catch (IllegalAccessException e) {
System.out.println("caught in main.");
}
}
}
Output:
Understanding Built-in Exceptions:
Exceptions that are already available in Java libraries are referred to as built-in exception. These
exceptions are able to define the error situation so that we can understand the reason of getting this
error.
class ExcepDemo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9;
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
}
}
Output:
Creating user defined Exceptions
Java provides us the facility to create our own exceptions which are basically derived classes of
Exception. Creating our own Exception is known as a custom exception or user-defined exception.
Basically, Java custom exceptions are used to customize the exception according to user needs. In
simple words, we can say that a User-Defined Exception or custom exception is creating your own
exception class and throwing that exception using the ‘throw’ keyword.
class MyException extends Exception{
String str1;
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("MyException Occurred: "+str1) ;
}
}
class Example1{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
throw new MyException("This is My error Message");
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
Output:
Packages:
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Userdefined Packages:
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.
pack/A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
packexample.java
import pack.*;
class packexample{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
pack/A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
packexample.java
import pack.A;
class packexample{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
pack/A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");}
}
packexample.java
class B{
public static void main(String args[]){
pack.A obj = new pack.A();
obj.msg();
}
}
Output:
Understanding Access Protection Importing packages: