Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

BE Java Module - 4

Module 4 covers Java packages, their advantages, and how to create and access them. It explains exception handling in Java, detailing types of exceptions, keywords used for handling exceptions, and provides examples of try-catch blocks. The document emphasizes the importance of maintaining the normal flow of applications through effective exception handling.

Uploaded by

varadaraj.navkis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

BE Java Module - 4

Module 4 covers Java packages, their advantages, and how to create and access them. It explains exception handling in Java, detailing types of exceptions, keywords used for handling exceptions, and provides examples of try-catch blocks. The document emphasizes the importance of maintaining the normal flow of applications through effective exception handling.

Uploaded by

varadaraj.navkis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Module – 4

Packages: Packages, Packages and Member Access, Importing 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.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You
can use any directory name like /home (in case of Linux), d:/abc (in case of
windows) etc. If you want to keep the package within the same directory, you
can use . (dot).

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple


Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
How to access package from another 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.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
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
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
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.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be
imported excluding the classes and interfaces of the subpackages. Hence, you
need to import the subpackage as well.

Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to
categorize the package further.

Let's take an example, Sun Microsystem has definded a package named java
that contains many classes like System, String, Reader, Writer, Socket etc.
These classes represent a particular group e.g. Reader and Writer classes are for
Input/Output operation, Socket and ServerSocket classes are for networking etc
and so on. So, Sun has subcategorized the java package into subpackages such
as lang, net, io etc. and put the Input/Output related classes in io package,
Server and ServerSocket classes in net packages and so on.
The standard of defining package is domain.company.package e.g.
com.javatpoint.bean or org.sssit.dao.
Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple


Output:Hello subpackage

How to send the class file to another directory or drive?


There is a scenario, I want to put the class file of A.java source file in classes
folder of c: drive. For example:

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.

e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple


Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of
java that tells where to look for class file. For example:
e:\sources> java -classpath c:\classes mypack.Simple
Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.
o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying
the jar file in the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be
saved by the public class name.
//save as C.java otherwise Compilte Time Error

class A{}
class B{}
public class C{}

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files
containing one public class, but keep the package name same. For example:
//save as A.java

package javatpoint;
public class A{}
//save as B.java

package javatpoint;
public class B{}
Exceptions: Exception-Handling Fundamentals, Exception Types,
Uncaught Exceptions, Using try and catch, Multiple catch clauses, Nested
try statements, throw, throws, finally, java’s Built-in Exceptions, Creating
your own exception subclasses, chained Exceptions.

Exception Handling:
The Exception Handling in Java is one of the powerful mechanism to handle
the runtime errors so that the normal flow of the application can be maintained.
What is 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.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of
the application. An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10.statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at
statement 5; the rest of the code will not be executed, i.e., statements 6 to 10
will not be executed. However, when we perform exception handling, the rest of
the statements will be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error. The hierarchy of Java
Exception classes is given below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException
and Error are known as checked exceptions. For example, IOException,
SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked
exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked
at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The
following table describes each.
Keyword Description

try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. 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 necessary code of the program.
It is executed whether 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 specifies that


there may occur an exception in the method. It doesn't throw an
exception. It is always used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-
catch statement to handle the exception.
JavaExceptionExample.java
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by
a try-catch block.
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They
are as follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the
variable throws a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has
characters; converting this variable into digit will cause
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException
occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException.
Consider the following statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It must
be used within the method.
If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute. So, it is recommended not to keep the code in try
block that will not throw an exception.

Java try block must be followed by either catch or finally block.


Syntax of Java try-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}
Java catch block
Java catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the parent class
exception ( i.e., Exception) or the generated exception type. However, the good
approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple
catch block with a single try block.
Internal Working of Java try-catch block

The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception
occurred).
o Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.

Problem without exception handling


Let's try to understand the problem if we don't use a try-catch block.
Example 1
TryCatchExample1.java
public class TryCatchExample1 {
public static void main(String[] args) {
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is not executed (in such
case, the rest of the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not
handled, all the code below the exception won't be executed.
Solution by exception handling
Let's see the solution of the above problem by a java try-catch block.
Example 2
TryCatchExample2.java
public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
As displayed in the above example, the rest of the code is executed, i.e.,
the rest of the code statement is printed.

Example 3
In this example, we also kept the code in a try block that will not throw an
exception.
TryCatchExample3.java
public class TryCatchExample3 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not ex
ceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the
block code will not execute.
Example 4
Here, we handle the exception using the parent class exception.
TryCatchExample4.java
public class TryCatchExample4 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}

Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5
Let's see an example to print a custom message on exception.
TryCatchExample5.java
public class TryCatchExample5 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println("Can't divided by zero");
}
}
}
Can't divided by zero
Example 6
Let's see an example to resolve the exception in a catch block.
TryCatchExample6.java
public class TryCatchExample6 {

public static void main(String[] args) {


int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}
Output:
25
Example 7
In this example, along with try block, we also enclose exception code in a catch
block.
TryCatchExample7.java
public class TryCatchExample7 {

public static void main(String[] args) {

try
{
int data1=50/0; //may throw exception

}
// handling the exception
catch(Exception e)
{
// generating the exception in catch block
int data2=50/0; //may throw exception

}
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Here, we can see that the catch block didn't contain the exception code. So, enclose
exception code within a try block and use catch block only to handle the exceptions.
Example 8
In this example, we handle the generated exception (Arithmetic Exception) with a
different type of exception class (ArrayIndexOutOfBoundsException).
TryCatchExample8.java

public class TryCatchExample8 {


public static void main(String[] args) {
try
{
int data=50/0; //may throw exception

}
// try to handle the ArithmeticException using ArrayIndexOutOfBoundsExcep
tion
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Example 9
Let's see an example to handle another unchecked exception.
TryCatchExample9.java
public class TryCatchExample9 {

public static void main(String[] args) {


try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

Output:

java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Example 10
Let's see an example to handle checked exception.

TryCatchExample10.java

import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class TryCatchExample10 {

public static void main(String[] args) {

PrintWriter pw;
try {
pw = new PrintWriter("jtp.txt"); //may throw exception
pw.println("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {

System.out.println(e);
}
System.out.println("File saved successfully");
}
1. }

Output:

File saved successfully


Multiple catch clauses
Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler
Points to remember
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.
Flowchart of Multi-catch Block

Example 1
Let's see a simple example of java multi-catch block.
public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occu
rs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:
Arithmetic Exception occurs
rest of the code

Nested try statements


Using a try block inside another try block is permitted. It is called as nested try
block. Every statement that we enter a statement in try block, context of that
exception is pushed onto the stack.
For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error
and the entire block itself may cause another error. In such cases, exception
handlers have to be nested.
Syntax:
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}

}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Java Nested try Example
Example 1
Let's see an example where we place a try block within another try block for
two different exceptions.

public class NestedTryBlock{


public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}

//catch block of inner try block 2


catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}

System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}

Output:

When any try block does not have a catch block for a particular exception, then
the catch block of the outer (parent) try block are checked for that exception,
and if it matches, the catch block of outer try block is executed.
If none of the catch block specified in the code is unable to handle the
exception, then the Java runtime system will handle the exception. Then it
displays the system generated message for that exception.
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

We can also define our own set of conditions and throw an exception explicitly
using throw keyword. 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 i.e.,
throw new exception_class("error message");
Let's see the example of throw IOException.
throw new IOException("sorry device error");
Where the Instance must be of type Throwable or subclass of Throwable. For
example, Exception is the sub class of Throwable and the user-defined
exceptions usually extend the Exception class.
Example 1: Throwing Unchecked Exception
In this example, we have created a method named validate() that accepts an
integer as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Output:
The above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.
Note: If we throw unchecked exception from a method, it is must to handle the
exception or declare in throws clause.
If we throw a checked exception using throw keyword, it is must to handle the
exception using catch block or the method must declare it using throws
declaration.

Example 2: Throwing Checked Exception


Note: Every subclass of Error and RuntimeException is an unchecked exception
in Java. A checked exception is everything else under the Throwable class.

TestThrow2.java
import java.io.*;

public class TestThrow2 {

//function to check if person is eligible to vote or not


public static void method() throws FileNotFoundException {

FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.


txt");
BufferedReader fileInput = new BufferedReader(file);
throw new FileNotFoundException();
}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}
Output:

Example 3: Throwing User-defined Exception


exception is everything else under the Throwable class.
TestThrow3.java
// class represents user-defined exception
class UserDefinedException extends Exception
{
public UserDefinedException(String str)
{
// Calling constructor of parent Exception
super(str);
}
}
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-
defined exception");
}
catch (UserDefinedException ude)
{
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
}
}
}
Output:

Throws:
Java throws keyword is used to declare an exception. It gives an information
to the programmer that there may occur an exception. So, it is better for the
programmer to provide the exception handling code so that the normal flow of
the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there
occurs any unchecked exception such as NullPointerException, it is
programmers' fault that he is not checking the code before it being used.
Syntax of Java throws
1. return_type method_name() throws exception_class_name{
2. //method code
3. }
Which exception should be declared?
Ans: Checked exception only, because:
o unchecked exception: under our control so we can correct our code.
o error: beyond our control. For example, we are unable to do anything if
there occurs VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
Java throws Example
Testthrows1.java
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either
caught or declare the exception.
There are two cases:
1. Case 1: We have caught the exception i.e. we have handled the exception
using try/catch block.
2. Case 2: We have declared the exception i.e. specified throws keyword
with the method.
Case 1: Handle Exception Using try-catch block
In case we handle the exception, the code will be executed fine whether
exception occurs during the program or not.
Testthrows2.java
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}

System.out.println("normal flow...");
}
}

Output:
exception handled
normal flow...
Case 2: Declare Exception
o In case we declare the exception, if exception does not occur, the code
will be executed fine.
o In case we declare the exception and the exception occurs, it will be
thrown at runtime because throws does not handle the exception.
Let's see examples for both the scenario.
A) If exception does not occur
Testthrows3.java
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exce
ption
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
Output:
device operation performed
normal flow...
B) If exception occurs
Testthrows4.java
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exce
ption
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
Output:

Difference between throw and throws in Java

Sr. Basis of Throw Throws


no. Differences

1. Definition Java throw keyword is Java throws keyword is used in


used throw an exception the method signature to declare
explicitly in the code, an exception which might be
inside the function or the thrown by the function while
block of code. the execution of the code.

2. Usage Type of exception Using Using throws keyword, we can


throw keyword, we can declare both checked and
only propagate unchecked unchecked exceptions.
exception i.e., the checked However, the throws keyword
exception cannot be can be used to propagate
propagated using throw checked exceptions only.
only.

3. Syntax The throw keyword is The throws keyword is


followed by an instance of followed by class names of
Exception to be thrown. Exceptions to be thrown.

4. Declaration throw is used within the throws is used with the method
method. signature.

5. Internal We are allowed to throw We can declare multiple


implementation only one exception at a exceptions using throws
time i.e. we cannot throw keyword that can be thrown by
multiple exceptions. the method. For example,
main() throws IOException,
SQLException.
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.
Flowchart of finally block

Note: If you don't handle the exception, before terminating the program, JVM
executes finally block (if any).
Why use Java finally block?
o finally block in Java can be used to put "cleanup" code such as closing a
file, closing connection, etc.
o The important statements to be printed can be placed in the finally block.
Usage of Java finally
Let's see the different cases where Java finally block can be used.
Case 1: When an exception does not occur
Let's see the below example where the Java program does not throw any
exception, and the finally block is executed after the try block.
TestFinallyBlock.java
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of phe code...");


}
}

Output:

Case 2: When an exception occurr but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however
the catch block cannot handle it. Despite this, the finally block is executed after
the try block and then the program terminates abnormally.
TestFinallyBlock1.java
public class TestFinallyBlock1{
public static void main(String args[]){

try {

System.out.println("Inside the try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


}
}

Output:
Case 3: When an exception occurs and is handled by the catch block
Example:
Let's see the following example where the Java code throws an exception and
the catch block handles the exception. Later the finally block is executed after
the try-catch block. Further, the rest of the code is also executed normally.
TestFinallyBlock2.java
public class TestFinallyBlock2{
public static void main(String args[]){

try {
System.out.println("Inside try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}

//handles the Arithmetic Exception / Divide by zero exception


catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


}
}
Output:
Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
Note: The finally block will not be executed if the program exits (either by
calling System.exit() or by causing a fatal error that causes the process to abort).
Rethowing exceptions:
Sometimes we may need to rethrow an exception in Java. If a catch block
cannot handle the particular exception it has caught, we can rethrow the
exception. The rethrow expression causes the originally thrown object to be
rethrown.
Because the exception has already been caught at the scope in which the
rethrow expression occurs, it is rethrown out to the next enclosing try block.
Therefore, it cannot be handled by catch blocks at the scope in which the
rethrow expression occurred. Any catch blocks for the enclosing try block have
an opportunity to catch the exception.
Syntax
catch(Exception e) {
System.out.println("An exception was thrown");
throw e;
}
Example:
public class RethrowException {
public static void test1() throws Exception {
System.out.println("The Exception in test1() method");
throw new Exception("thrown from test1() method");
}
public static void test2() throws Throwable {
try {
test1();
} catch(Exception e) {
System.out.println("Inside test2() method");
throw e;
}
}
public static void main(String[] args) throws Throwable {
try {
test2();
} catch(Exception e) {
System.out.println("Caught in main");
}
}
}

Output
The Exception in test1() method
Inside test2() method
Caught in main
Exception specification:
Built in exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of
important built-in exceptions in Java.
Examples of Built-in Exception:
1. Arithmetic exception : It is thrown when an exceptional condition has
occurred in an arithmetic operation.
// Java program to demonstrate ArithmeticException

class ArithmeticException_Demo {
public static void main(String[] args) {
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
} catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}
Output
Can't divide a number by 0
2. ArrayIndexOutOfBounds Exception: It is thrown to indicate that an array
has been accessed with an illegal index. The index is either negative or greater
than or equal to the size of the array.
// Java program to demonstrate ArrayIndexOutOfBoundException

class ArrayIndexOutOfBound_Demo {
public static void main(String[] args) {
try {
int[] a = new int[5];
a[5] = 9; // accessing 6th element in an array of size 5
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
Output
Array Index is Out Of Bounds

3. ClassNotFoundException : This Exception is raised when we try to access a


class whose definition is not found.
// Java program to illustrate the concept of ClassNotFoundException
class College {

}
class Navkis {
}

class MyClass {
public static void main(String[] args) {
try {
Object o = Class.forName(args[0]).newInstance();
System.out.println("Class created for " + o.getClass().getName());
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException e) {
System.out.println("Exception occurred: " + e.getMessage());
}
}
}

Output:
ClassNotFoundException

4. FileNotFoundException : This Exception is raised when a file is not


accessible or does not open.
// Java program to demonstrate FileNotFoundException

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

class File_notFound_Demo {
public static void main(String[] args) {
try {
// Following file does not exist
File file = new File("file.txt");
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}

Output
File does not exist

5. IOException : It is thrown when an input-output operation failed or


interrupted
// Java program to illustrate IOException
import java.io.*;

class IOE {
public static void main(String[] args) {
try {
FileInputStream f = new FileInputStream("abc.txt");
int i;
while ((i = f.read()) != -1) {
System.out.print((char)i);
}
f.close();
} catch (IOException e) {
System.out.println("IOException occurred: " + e.getMessage());
}
}
}
Output:
error: unreported exception IOException; must be caught or declared to be
thrown
6. InterruptedException : It is thrown when a thread is waiting, sleeping, or
doing some processing, and it is interrupted.
// Java Program to illustrate InterruptedException
class InterruptedException {
public static void main(String args[])
{
Thread t = new Thread();
t.sleep(10000);
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared to
be thrown

7. NoSuchMethodException : t is thrown when accessing a method which is


not found.
// Java Program to illustrate NoSuchMethodException
class NSME {
public NSME() {
try {
Class<?> i = Class.forName("java.lang.String");
try {
i.getMethod("someMethod", Class[].class);
} catch (SecurityException | NoSuchMethodException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {


new NSME();
}
}
}
Output:
error: exception NoSuchMethodException is never thrown
in body of corresponding try statement
8. NullPointerException : This exception is raised when referring to the
members of a null object. Null represents nothing
// Java program to demonstrate NullPointerException
class NullPointer_Demo {
public static void main(String[] args) {
try {
String a = null; // null value
System.out.println(a.charAt(0));
} catch (NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}

Output:
NullPointerException..

9. NumberFormatException : This exception is raised when a method could


not convert a string into a numeric format.
// Java program to demonstrate NumberFormatException
class NumberFormat_Demo {
public static void main(String[] args) {
try {
// "navkis" is not a number
int num = Integer.parseInt("navkis");
System.out.println(num);
} catch (NumberFormatException e) {
System.out.println("Number format exception");
}
}
}

Output:
Number format exception
10. StringIndexOutOfBoundsException : It is thrown by String class methods
to indicate that an index is either negative than the size of the string.

// Java program to demonstrate StringIndexOutOfBoundsException

class StringIndexOutOfBound_Demo {
public static void main(String[] args) {
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}

Output:
StringIndexOutOfBoundsException

Creating own exception sub classes


Java provides rich set of built-in exception classes like: ArithmeticException,
IOException, NullPointerException etc. all are available in the java.lang
package and used in exception handling. These exceptions are already set to
trigger on pre-defined conditions such as when you divide a number by zero it
triggers ArithmeticException.
Apart from these classes, Java allows us to create our own exception class to
provide own exception implementation. These type of exceptions are called
user-defined exceptions or custom exceptions.
You can create your own exception simply by extending java Exception class.
You can define a constructor for your Exception (not compulsory) and you can
override the toString() function to display your customized message on catch.
Example: Custom Exception
In this example, we are creating an exception class MyException that extends
the Java Exception class and
class MyException extends Exception
{
private int ex;
MyException(int a)
{
ex = a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}

class Demo
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a); //calling constructor of user-defined exception
class
}
else
{
System.out.println(a+b);
}
}

public static void main(String[] args)


{
try
{
sum(-10, 10);
}
catch(MyException me)
{
System.out.println(me); //it calls the toString() method of user-defined
Exception
}
}
}
Output:
MyException[-10] is less than zero

Example: Custom Exception


Here we created a class ItemNotFound that extends the Exception class and
helps to generate our own exception implementation.

class ItemNotFound extends Exception


{
public ItemNotFound(String s) {
super(s);
}
}

class Demo
{
static void find(int arr[], int item) throws ItemNotFound
{
boolean flag = false;
for (int i = 0; i < arr.length; i++) {
if(item == arr[i])
flag = true;
}
if(!flag)
{
throw new ItemNotFound("Item Not Found"); //calling constructor of user-
defined exception class
}
else
{
System.out.println("Item Found");
}
}

public static void main(String[] args)


{
try
{
find(new int[]{12,25,45}, 10);
}
catch(ItemNotFound i)
{
System.out.println(i);
}
}
}

Output:
ItemNotFound: Item Not Found

You might also like