0% found this document useful (0 votes)
35 views137 pages

Unit 6 - PNR - Part 1

The document discusses exception handling in Java including try, catch, and throw keywords as well as exception types. It covers defining custom exception classes, and using exceptions with file input/output and abstract classes/interfaces.

Uploaded by

Akanksha Bhagat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views137 pages

Unit 6 - PNR - Part 1

The document discusses exception handling in Java including try, catch, and throw keywords as well as exception types. It covers defining custom exception classes, and using exceptions with file input/output and abstract classes/interfaces.

Uploaded by

Akanksha Bhagat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
You are on page 1/ 137

Unit 6

Exception Handling, I/O, abstract


classes and interfaces

Dr. Purvi Ramanuj


DR. PURVI RAMANUJ
Exception Handling, I/O, abstract classes
and interfaces:
• Exception types, finally clause, rethrowing
Exceptions, chained exceptions, defining
custom exception classes,
• file class and its input and output, Reading
data from web,
• Abstract classes,
• interfaces, Comparable and Cloneabal
interface.

Dr. Purvi Ramanuj


Chapter 11

Exception Handling

Dr. Purvi Ramanuj


Content
What is an Exception?
Exception-handling in Java
try-catch()
try with multiple catch
nested try catch
-finally Statement
Throw keyword
Exception Hierarchy
Throws keyword
Chained Exceptions
Explicit and Implicit Exceptions
Creating Your Own Exception
Dr. Purvi Ramanuj
Introduction to Errors and Types of Errors

• In Java, errors can be divided into two categories:


– Compile time errors
– Runtime errors
• Compile time errors are syntactic errors during writing of the
program.
• Most common examples of compile time errors are missing
semicolon, comma, double quotes, etc.
• They occur mainly due to poor understanding of language or
lack of concentration in writing the program.
• Logical errors occur mainly due to improper understanding of
the program logic by the programmer.
• Logical errors cause the unexpected or unwanted output.
Dr. Purvi Ramanuj
Introduction to Exceptions
• Java provides exception handling mechanism,
which can be used to trap this exception and
run programs smoothly after catching the
exception.
• Examples:
– Division by zero.
– Opening file which does not exist.
– Insufficient memory.
– Violating array bounds.
– Others.
Dr. Purvi Ramanuj
What Is Exception?

• An exception is an event that occurs during


the execution of a program, which disrupts
the normal flow of the program’s instructions

Dr. Purvi Ramanuj


class ThrowsExecp{
public static void main(String args[]){
String str = null;
System.out.println(str.length());
}
}

Dr. Purvi Ramanuj


java ThrowsExecp

Exception in thread "main"


java.lang.NullPointerException: Cannot invoke
"String.length()" because "<local1>" is null
at ThrowsExecp.main(ThrowsExecp.java:4)

Dr. Purvi Ramanuj


class GFG {
public static void main (String[] args) {

// array of size 4.
int[] arr = new int[4];

// this statement causes an exception


int i = arr[4];

// the following statement will never execute


System.out.println("Hi, I want to execute");
}
}
Dr. Purvi Ramanuj
• Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 4
at GFG.main(GFG.java:9)

Dr. Purvi Ramanuj


• use FileReader class in your program to read
data from a file, if the file specified in its
constructor doesn't exist, then
a FileNotFoundException occurs, and the
compiler prompts the programmer to handle
the exception.

Dr. Purvi Ramanuj


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

public class FilenotFound_Demo {

public static void main(String args[]) {


File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
Dr. Purvi Ramanuj
• C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported
exception FileNotFoundException; must be
caught or declared to be thrown FileReader fr
= new FileReader(file); ^ 1 error

Dr. Purvi Ramanuj


public class Unchecked_Demo {

public static void main(String args[]) {


int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}

Dr. Purvi Ramanuj


• Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 5
at
Exceptions.Unchecked_Demo.main(Unchecke
d_Demo.java:8)

Dr. Purvi Ramanuj


Exception Object and Throwing Exceptions

• When an error occurs within a method, the method


creates an object and hands it off to the runtime
system. The object is called an exception object.

• Exception object contains information about the


error, including its type and the state of the program
when the error occurred.

• Creating an exception object and handing it to the


runtime system is called throwing an exception.

Dr. Purvi Ramanuj


Searching Exception Handler
• The runtime system searches the call stack for a
method which contains a block of code that can
handle the exception.
• This block of code is called an exception handler.
• The search begins with the method in which the
error occurred and proceeds through the call
stack in the reverse order in which the methods
were called.
• When an appropriate handler is found, the
runtime system passes the exception to the
handler.
• An exception handler is considered appropriate if
the type of the exception object thrown matches
the type that can be handled by the handler.

Dr. Purvi Ramanuj


Exception Handling Mechanism
• In Java, exceptions are objects which are thrown.
• All such codes which might throw an exception during the execution of
the program must be placed in the try block.
• The exception thrown must be caught by the catch block.
• If not caught, the particular program may terminate abnormally.

Dr. Purvi Ramanuj


Exception Handling Mechanism: Try and Catch
Block
• This try block is known as exception-generated block or guarded
region.
• The catch block is responsible for catching the exception thrown by
the try block. It is also known as exception handler block.
• When the try block throws an exception, the control of the program
passes to the catch block, and if argument matches, the exception is
caught.
• In case no exception is thrown, the catch block is ignored and control
passes to the next statement after the catch block.

Dr. Purvi Ramanuj


Syntax of Exception-Handling Construct
try
{
statements;
}
catch(Exceptionclass1 object) {
statements for handling the exception;
}
catch(Exceptionclass1 object){
statements for handling the exception;
}
...........
finally{
//statements executed before method returns
}
Dr. Purvi Ramanuj
Exception Handling Using Try and Catch
import java.lang.*;
class main
{
public static void main(String args[])
{
try
{
int num;
num=Integer.parseInt("ABC123");
System.out.println("Control won't reach here");
}
catch(NumberFormatException E)
{
System.out.println("Exception thrown");
System.out.println(E.getMessage());
}
System.out.println("Out of try-catch block");
}
} Dr. Purvi Ramanuj
OUTPUT:
Exception thrown
For input string: "ABC123"
Out of try-catch block

Dr. Purvi Ramanuj


NumberFormatException in Java

• is thrown when we try to convert a string into


a numeric value such as float or integer, but
the format of the input string is not
appropriate or illegal.

Dr. Purvi Ramanuj


Common reasons for NumberFormatException
• The input string provided might be null-
Example- Integer.parseInt(null);
• The input string might be empty-
Example- Integer.parseInt("");
• The input string might be having trailing space-
Example- Integer.parseInt("123 ");
• The input string might be having a leading space-
Example- Integer.parseInt(" 123");
• The input string may be alphanumeric-
Example- Long.parseLong("b2");
• The input string may have an input which might exceed the range of the datatype storing the parsed
string-
Example- Integer.parseInt("135"); The maximum possible value of integer can be 127, but the value
in the string is 135 which is out of range, so this will throw the exception.
• There may be a mismatch between the input string and the type of the method which is being used
for parsing. If you provide the input string like "1.0" and you try to convert this string into an integer
value, it will throw a NumberFormatException exception.
Example- Integer.parseInt("1..0");

Dr. Purvi Ramanuj


Catching a Single Exception
int qty;
String s = getQtyFromForm();

try {
// Might throw NumberFormatException
qty = Integer.parseInt(s);
}

catch ( NumberFormatException e ) {
// Handle the exception

}
// If no exceptions were thrown, we end up here

Dr. Purvi Ramanuj


Example : ArithmeticException
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...");
}
}
Dr. Purvi Ramanuj
we handle the exception using the parent
class exception.
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");
}

Dr. Purvi Ramanuj


• Write a program for array declared with 2
elements. Then the code tries to access the
3rd element of the array which throws an
exception. Catch that exception

Dr. Purvi Ramanuj


import java.io.*;

public class ExcepTest {

public static void main(String args[]) {


try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
Dr. Purvi Ramanuj
• Exception
thrown :java.lang.ArrayIndexOutOfBoundsExc
eption: 3 Out of the block

Dr. Purvi Ramanuj


Try With Multiple Catch
• Sometimes it is possible that a single try block may throw
exceptions of different types at run time.
• If any of the exception is not handled that might be thrown, a
premature termination of the program occurs.
• To catch all such types of exception, one catch block can be
placed per exception that might be generated within the try
block.
• Depending on what type of exception thrown, corresponding
catch blocks catches the exception object thrown by the try
block.

Dr. Purvi Ramanuj


Try With Multiple Catch
• The general syntax is as follows:
try
{
Statement1;
Statement2;
}
Catch(ExceptionClass1)
{
}
Catch(ExceptionClass2)
{
}
Catch(ExceptionClass3)
{
}

Dr. Purvi Ramanuj


Catching Multiple Exceptions
try {
// Might throw MalformedURLException
URL u = new URL(str);
// Might throw IOException
URLConnection c = u.openConnection();
}
catch (MalformedURLException e) {
System.err.println("Could not open URL: " + e);
}
catch (IOException e) {
System.err.println("Could not connect: " + e);
Dr. Purvi Ramanuj
}
Catching Any Exception
• It is possible to create a handler that catches any type of exception.
• It is done by catching the base-class type exception (there are other types
of base exceptions, but exception is the base that is pertinent to virtually
all programming activities):
catch(Exception e)
{
System.out.println("Caught an exception");
}
• This will catch any exception, so if you use it, you will want to put it at the
end of your list of handlers to avoid preempting any exception handlers
that might otherwise follow it.

Dr. Purvi Ramanuj


Try this program
• Make a program using try-catch blocks. User
enters two command line arguments and
divides the first argument by second.
• If the second argument is zero than catch the
appropriate exception. If user enters only one
value handle the appropriate exception.

Dr. Purvi Ramanuj


class pb1
{
public static void main(String args[])
{ try{
int n1,n2;
n1=Integer.parseInt(args[0]);
n2=Integer.parseInt(args[1]);
System.out.println("Div result="+n1/n2);
}
catch(ArithmeticException e)
{
System.out.println("You can not divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("YOu have entered only one number");
System.out.println("Please Enter two numbers");
}
}
}

Dr. Purvi Ramanuj


Nesting of try-catch Block: Syntax
try {
//statements
//statements
try
{
//statements
//statements
}
catch(<exception_two> obj)
{
//statements
}
//statements
//statements
}
catch(<exception_two> obj)
{
//statements
} Dr. Purvi Ramanuj
class NestingDemo{
public static void main(String args[]){
//main try-block catch(ArithmeticException e3){
try{ System.out.print("Arithmetic
//try-block2 Exception");
try{ System.out.println(" handled
//try-block3 in main try-block");
try{
}
int arr[]= {1,2,3,4};
/* I'm trying to display the value of
* an element which doesn't exist. The
catch(ArrayIndexOutOfBoundsException
* code should throw an exception e4){
*/
System.out.println(arr[10]); System.out.print("ArrayIndexOutOfBou
}catch(ArithmeticException e){ ndsException");
System.out.print("Arithmetic Exception"); System.out.println(" handled
System.out.println(" handled in try-block3"); in main try-block");
} }
}
catch(Exception e5){
catch(ArithmeticException e){
System.out.print("Exception");
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
System.out.println(" handled
} in main try-block");
} } }}

Dr. Purvi Ramanuj


Find output
• ArrayIndexOutOfBoundsException handled in
main try-block

Dr. Purvi Ramanuj


The finally Clause
• There is often some piece of code that one wants to execute
whether or not an exception is thrown within a try block.
• This usually pertains to some operation other than memory
recovery (since that is taken care of by the garbage
collector).
• To achieve this effect, a finally clause is used at the end
of all the exception handlers.
• The finally executes all the time irrespective of whether
an exception is thrown or not.
• Even if an exception is thrown and handled or not,
finally will execute.
• The finally block is guaranteed to execute after the try-catch
block.
Dr. Purvi Ramanuj
• The finally clause is an optional and its usage
is up to the programmer.
• The finally clause is necessary in some kind
of cleanup like an open file or network
connection, something you have drawn on
the screen, etc.

Dr. Purvi Ramanuj


Dr. Purvi Ramanuj
The finally Clause: Syntax
try {
//The guarded region: harmful activities
//that might throw A, B or C.
}
catch(A a1) {
//Handler for argument
}
catch(B b1) {
//Handler for situation B
}
catch(C c1) {
//Handler for situation C
}
finally {
//Activities that happen every time
}

Dr. Purvi Ramanuj


java finally example where exception
doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Dr. Purvi Ramanuj
• Output:
5
finally block is always executed
rest of the code...

Dr. Purvi Ramanuj


finally example where exception occurs
and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Dr. Purvi Ramanuj
• Output:
finally block is always executed
Exception in thread main
java.lang.ArithmeticException:/ by zero

Dr. Purvi Ramanuj


finally example where exception occurs
and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Dr. Purvi Ramanuj
• Output:
Exception in thread main
java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...

Dr. Purvi Ramanuj


Find output:
class JavaFinally
{
public static void main(String args[])
{
System.out.println(JavaFinally.myMethod());
}
public static int myMethod()
{
try {
return 112;
}
finally {
System.out.println("This is Finally block");
System.out.println("Finally block ran even after return statement");
}
}
}
Dr. Purvi Ramanuj
Output:
finally executes even after return
This is Finally block
Finally block ran even after return statement
112

Dr. Purvi Ramanuj


Find Output
public class ExcepTest {

public static void main(String args[]) {


int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}

Dr. Purvi Ramanuj


Exception
thrown :java.lang.ArrayIndexOutOfBoundsExcep
tion: 3
First element value: 6
The finally statement is executed

Dr. Purvi Ramanuj


• Write a program to take a number from user ,
convert it into interger , handle number
format exception

Dr. Purvi Ramanuj


public class NumberFormatException {
static void numberConversion(String input){
try{
int number = Integer.parseInt(input);
System.out.println("The input integer after conversion is : "+number);
}catch(java.lang.NumberFormatException e){
System.out.println("Error!!! While converting input to integer");
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the string to be converted to an integer : ");
String input = scanner.nextLine();
numberConversion(input);
}
}
Dr. Purvi Ramanuj
Common scenario of Exception Handling
where exceptions may occur
1) Common scenario where ArithmeticException occurs

int a=50/0;

2) Scenario where NullPointerException occurs

String s=null;
S.O.P(s.length());

Dr. Purvi Ramanuj


Common scenario of Exception Handling
where exceptions may occur
3)Scenario where NumberFormatException Occurs

The wrong formatting of any value may occur


NumberFormatException.

For E.g
String s="abc";
int i=Integer.parseInt(s);

Dr. Purvi Ramanuj


Common scenario of Exception Handling
where exceptions may occur
4) Scenario where ArrayIndexOutOfBoundsException Occurs

Eg:
int a[]=new int[4];
a[10]=50

Dr. Purvi Ramanuj


Cases when the finally block doesn’t execute

• The circumstances that prevent execution of


the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally
block.

Dr. Purvi Ramanuj


The throw Keyword
• The Java runtime system was responsible for throwing the
exceptions.
• All those exceptions come under the category of implicit
exceptions.
• If we want, we can throw exceptions manually or explicitly.
• For that, Java provides the keyword throw.
• The throw keyword can be used to throw an exception explicitly.
• It can be used to re-throw an exception which has already been
thrown.
• The throw statement requires a single argument: a throwable
object.
• Throwable objects are instances of any subclass of the throwable
class.
• Example
throw someThrowableObject;
Dr. Purvi Ramanuj
• We can define our own set of conditions or rules
and throw an exception explicitly using throw
keyword.
• For example, we can throw ArithmeticException
when we divide number by 5, or any other
numbers,
• what we need to do is just set the condition and
throw any exception using throw keyword.
• Throw keyword can also be used for throwing
custom exceptions.
Dr. Purvi Ramanuj
The throw Keyword: An Example
public int pop()
{
int obj;
if(top ==o)
{
throw new EmptyStackException();
}
obj = arr[top--];
return obj;
}

Dr. Purvi Ramanuj


public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Dr. Purvi Ramanuj
Exception in thread main
java.lang.ArithmeticException:not valid

Dr. Purvi Ramanuj


• Write a program for checking the Student age
if the student age<12 and weight <40 then our
program should return that the student is not
eligible for registration.

Dr. Purvi Ramanuj


public class ThrowExample {
static void checkEligibilty(int stuage, int stuweight){
if(stuage<12 && stuweight<40) {
throw new ArithmeticException("Student is not eligible for registration");
}
else {
System.out.println("Student Entry is Valid!!");
}
}

public static void main(String args[]){


System.out.println("Welcome to the Registration process!!");
checkEligibilty(10, 39);
System.out.println("Have a nice day..");
}
}

Dr. Purvi Ramanuj


Welcome to the Registration process!!
Exception in thread "main"
java.lang.ArithmeticException: Student is not
eligible for registration at
beginnersbook.com.ThrowExample.checkEligi
bilty(ThrowExample.java:9) at
beginnersbook.com.ThrowExample.main(Thro
wExample.java:18)

Dr. Purvi Ramanuj


• The throw statement is used together with
an exception type.
• There are many exception types available in
Java: ArithmeticException, ClassNotFoundExce
ption, ArrayIndexOutOfBoundsException, Secu
rityException, etc.

Dr. Purvi Ramanuj


public double divide(double a, double b) {
if (b == 0) {
throw new ArithmeticException("Divider cannot be equal
to zero!");
}
return a / b;
}
• As you can see, we have used ArithmeticException with
perfectly fits our needs. We can pass a
single String constructor parameter which is exception
message.
Dr. Purvi Ramanuj
• The flow of execution of the program stops
immediately after the throw statement is executed
and the nearest enclosing try block is checked to
see if it has a catch statement that matches the
type of exception.
• If it finds a match, controlled is transferred to that
statement otherwise next enclosing try block is
checked and so on. If no matching catch is found
then the default exception handler will halt the
program.
Dr. Purvi Ramanuj
Find Output
class ThrowExcep
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}
public static void main(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}

Dr. Purvi Ramanuj


• Caught inside fun().
• Caught in main.

Dr. Purvi Ramanuj


Exception Hierarchy

Dr. Purvi Ramanuj


Dr. Purvi Ramanuj
Types of Exception:
1. Checked Exception
2. Unchecked Exception
3. Error

Dr. Purvi Ramanuj


Types of Exceptions
• All exceptions in Java are objects of Throwable class
1. Checked Exceptions
– are exceptions derived from Exception class excluding the RuntimeException
class
– must be handled explicitly
– are checked by the compiler
– e.g. IOException, SQLException

2. Unchecked Exceptions
– are exceptions derived from Error and RuntimeException classes
– are usually irrecoverable and not handled explicitly
– are not checked by the compiler but they are checked at runtime.
– e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException

• Both checked and unchecked exceptions can be thrown and caught


• New exceptions are created by extending the Exception class or its subclasses
Dr. Purvi Ramanuj
Types of Exception:
3. Error

Error is irrecoverable

For E.g-OutOfMemoryError etc

Dr. Purvi Ramanuj


Runtime Exception
• There is a whole group of exception types in this category.
• They are always thrown automatically by Java and one does not need to
include them in exception specifications.
• Conveniently enough, they are all grouped together under a single base
class called RunTimeException.
• It establishes a family of types that have some characteristics and
behaviours in common.
• Also, one never needs to write an exception specification because a
method might throw a RunTimeException.
• Because they indicate bugs, RunTimeException is not usually caught; it is
dealt with automatically.

Dr. Purvi Ramanuj


list of Java Checked Exceptions Defined in java.lang
Sr.No Exception & Description
1 ClassNotFoundException
Class not found.

2 CloneNotSupportedException
Attempt to clone an object that does not implement the Cloneable interface.

3 IllegalAccessException
Access to a class is denied.

4 InstantiationException
Attempt to create an object of an abstract class or interface.

5 InterruptedException
One thread has been interrupted by another thread.

6 NoSuchFieldException
A requested field does not exist.

7 NoSuchMethodException
A requested method does not exist

Dr. Purvi Ramanuj


List of Java Unchecked RuntimeException.
Sr.No. Exception & Description

1 ArithmeticException
Arithmetic error, such as divide-by-zero.

2 ArrayIndexOutOfBoundsException
Array index is out-of-bounds.

3 ArrayStoreException
Assignment to an array element of an incompatible type.

4 ClassCastException
Invalid cast.

5 IllegalArgumentException
Illegal argument used to invoke a method.

6 IllegalMonitorStateException
Illegal monitor operation, such as waiting on an unlocked thread.

Dr. Purvi Ramanuj


7 IllegalStateException
Environment or application is in incorrect state.
8 IllegalThreadStateException
Requested operation not compatible with the current thread state.
9 IndexOutOfBoundsException
Some type of index is out-of-bounds.
10 NegativeArraySizeException
Array created with a negative size.
11 NullPointerException
Invalid use of a null reference.
12 NumberFormatException
Invalid conversion of a string to a numeric format.
13 SecurityException
Attempt to violate security.
14 StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
15 UnsupportedOperationException
An unsupported operation was encountered.

Dr. Purvi Ramanuj


Throws keyword
• two types of exception : checked and unchecked.
• Checked exception (compile time) force you to
handle them, if you don’t handle them then the
program will not compile.
• On the other hand unchecked exception (Runtime)
doesn’t get checked during compilation.
• Throws keyword is used for handling checked
exceptions . By using throws we can declare
multiple exceptions in one go.

Dr. Purvi Ramanuj


• throws is a keyword in Java which is used in
the signature of method to indicate that this
method might throw one of the listed type
exceptions.
• The caller to these methods has to handle the
exception using a try-catch block.
• catching is optional if the exceptions are of
type unchecked exceptions

Dr. Purvi Ramanuj


Syntax
type method_name(parameter_list) throws
exception_list
{
//definition of method
}

Dr. Purvi Ramanuj


import java.io.*;
class file1{
public static void main(String[] args) throws
IOException{
FileWriter file = new FileWriter("c:\\Data1.txt");
file.write(“data");
file.close();
}
}
Dr. Purvi Ramanuj
Another solution is to use try catch
import java.io.*;
class file1{
public static void main(String[] args) {
try{
FileWriter file = new FileWriter("c:\\Data1.txt");
file.write(“data");
file.close();
}
catch(IOException){}
}
}
Dr. Purvi Ramanuj
question
• What is the need of having throws keyword
when you can handle exception using try-
catch?

Dr. Purvi Ramanuj


• suppose you have several such methods that
can cause same exceptions, in that case it
would be tedious to write these try-catch for
each method. The code will become
unnecessary long and will be less-readable.

Dr. Purvi Ramanuj


Solution with try catch
public void myMethod()
{
try {
// Statements that might throw an exception
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}
Dr. Purvi Ramanuj
Solution with throws
public void myMethod() throws ArithmeticException, NullPointerException
{
// Statements that might throw an exception
}

//can have multiple methods throwing same exception without handling it


public static void main(String args[]) {
try {
myMethod();
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}

Dr. Purvi Ramanuj


In this example the method myMethod() is throwing two checked exceptions so we
have declared these exceptions in the method signature using throws Keyword. If we
do not declare these exceptions then the program will throw a compilation error.

import java.io.*;
class ThrowExample {
void myMethod(int num)throws IOException, ClassNotFoundException{
if(num==1)
throw new IOException("IOException Occurred");
else
throw new ClassNotFoundException("ClassNotFoundException");
}
}

public class Example1{


public static void main(String args[]){
try{
ThrowExample obj=new ThrowExample();
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}
}

Dr. Purvi Ramanuj


• java.io.IOException: IOException Occurred

Dr. Purvi Ramanuj


• There are two cases:

Dr. Purvi Ramanuj


• If you are calling a method that declares an
exception, you must either caught or declare
the exception.
• There are two cases:
• Case1:You caught the exception i.e. handle the
exception using try/catch.
• Case2:You declare the exception i.e. specifying
throws with the method.

Dr. Purvi Ramanuj


Case1:You caught the exception i.e. handle
the exception using try/catch
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...");
}
}
Dr. Purvi Ramanuj
Output:exception handled
normal flow...

Dr. Purvi Ramanuj


Case2: You declare the exception

• Case A)In case you declare the exception, if


exception does not occur, the code will be
executed fine.
• Case B)In case you declare the exception if
exception occures, an exception will be
thrown at runtime because throws does not
handle the exception.

Dr. Purvi Ramanuj


A)Program if exception does not occur
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 exception
M m=new M();
m.method();

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

Dr. Purvi Ramanuj


Output:device operation performed
normal flow...

Dr. Purvi Ramanuj


B.Program if exception occurs
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 exception
M m=new M();
m.method();

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

Dr. Purvi Ramanuj


• Output:Runtime Exception

Dr. Purvi Ramanuj


throw throws
•Syntax:throw is followed by an object •Syntax:throws is followed by a class
(new type) •and used with the method signature
•used inside the method
It is used to create a new Exception object It is used in method definition, to declare
and throw it that a risky method is being called.
Using throw keyword you can declare only Using throws keyword you can declare
one Exception at a time multiple exception at a time.
Example: Example:
throw new IOException("can not open throws IOException,
connection"); ArrayIndexBoundException;
throw keyword is used to throw an throws keyword is used to declare an
exception explicitly. exception possible during its execution.
throw keyword is followed by an instance throws keyword is followed by one or
of Throwable class or one of its sub- more Exception class names separated by
classes. commas.

Dr. Purvi Ramanuj


• throw an exception if age is below 18 (print
"Access denied"). If age is 18 or older, print
"Access granted":

Dr. Purvi Ramanuj


public class MyClass {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least
18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}
}
Dr. Purvi Ramanuj
Find Output
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.");
}
}
}

Dr. Purvi Ramanuj


• Inside fun().
• caught in main.

Dr. Purvi Ramanuj


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...");
}
}
Dr. Purvi Ramanuj
• Output:exception handled
• normal flow...

Dr. Purvi Ramanuj


• throws keyword is required only for checked
exception and usage of throws keyword for
unchecked exception is meaningless.
• throws keyword is required only to convince
compiler and
• usage of throws keyword does not prevent
abnormal termination of program.
• By the help of throws keyword we can provide
information to the caller of the method about the
exception.
Dr. Purvi Ramanuj
list of important methods available in the Throwable class.
No. Method & Description
1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.

2 public Throwable getCause()


Returns the cause of the exception as represented by a Throwable object.

3 public String toString()


Returns the name of the class concatenated with the result of getMessage().

4 public void printStackTrace()


Prints the result of toString() along with the stack trace to System.err, the error
output stream.

5 public StackTraceElement [] getStackTrace()


Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the
method at the bottom of the call stack.

6 public Throwable fillInStackTrace()


Fills the stack trace of this Throwable object with the current stack trace, adding to
any previous information in the stack trace.
Dr. Purvi Ramanuj
Chained Exceptions :
• Sometimes, you may need to throw a new
exception (with additional information) along
with the original exception.
• This is called chained exceptions.

Dr. Purvi Ramanuj


Example of create and throw
chained exceptions.
public class ChainedExceptionDemo {
public static void main(String[] args) {
try {
method1();
}
catch (Exception ex) {
ex.printStackTrace();
}
}

public static void method1() throws Exception {


try {
method2();
}
catch (Exception ex) {
throw new Exception("New info from method1", ex); // chained exception
}
}
public static void method2() throws Exception {
throw new Exception("New info from method2");
}
}

Dr. Purvi Ramanuj


java.lang.Exception: New info from method1
at ChainedExceptionDemo.method1(ChainedExceptionDemo.java:16)
at ChainedExceptionDemo.main(ChainedExceptionDemo.java:4)
Caused by: java.lang.Exception: New info from method2
at ChainedExceptionDemo.method2(ChainedExceptionDemo.java:21)
at ChainedExceptionDemo.method1(ChainedExceptionDemo.java:13)
... 1 more

Dr. Purvi Ramanuj


Exception Handling Mechanism: Explicit and
Implicit Exceptions
• An exception can be thrown explicitly or implicitly.
• Exception can be explicitly thrown using the keyword throw.
• In explicit exception, a method must tell what type of exception it might
throw.
• This can be done by using the throw keyword.
• All the other exceptions thrown by the Java runtime system are known
as implicit exceptions.
• A final clause may be put after the try-catch block, which executes
before the method returns.
• A try block must have a corresponding catch block, though it may have a
number of catch blocks.

Dr. Purvi Ramanuj


Keyword Description

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. It means, we can't use
try block alone.
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 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
doesn't throw an exception. It specifies that there may
occur an exception in the method. It is always used with
method signature.

Dr. Purvi Ramanuj


Creating Your Own Exception

• To create your own exception, you will need


to make Exception or Throwable class as
the base class of the class which you are
going to create.

• We have seen that Throwable class is the


top most class in the exception class
hierarchy, so all the methods of Throwable
class can be used by the derived class.

Dr. Purvi Ramanuj


Creating Your Own Exception: An Example
class demo extends Exception {
demo(String s) {
super(s);
}
}
class JPS15 {
public static void main(String[] args) {
try {
throw new demo("\n Hello from own
exception");
}
catch (demo E) {
System.out.println(E.getMessage());
}
}
}
Dr. Purvi Ramanuj
Find output -1
class MyException extends Exception {

// A Class that uses above MyException


public class setText {
// Driver Program
public static void main(String args[]) {
try {
// Throw an object of user defined exception
throw new MyException();
}
catch (MyException ex) {
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
Dr. Purvi Ramanuj
• Caught
• null

Dr. Purvi Ramanuj


Example 2
• Write an application that generates custom
exception if first argument from command line
argument is 0.

Dr. Purvi Ramanuj


class Zero extends Exception {
Zero() {
System.out.println("Zero Exception Generated");
}
}
class pb3 {
public static void main(String args[]) {
System.out.println("**////~~~~~~~~~Exception Demo~~~~~~~~~~////**");
try{
if(Integer.parseInt(args[0])==0)
throw new Zero();
}
catch(Zero z) {
System.out.println("You have entered Zero! Please give some another number in
command line argument");
}
}
}

Dr. Purvi Ramanuj


Example 3
• Write an application that generates custom
exception if any of its command line
arguments are negative.

Dr. Purvi Ramanuj


class Negative extends Exception {
Negative() {
System.out.println("Negative eXception generated");
}
}
class pb4 {
public static void main(String args[]) {
System.out.println("****/////Negative Exception Demo///////******");
try {
for(int i=0;i<args.length;i++) {
if(Integer.parseInt(args[i]) < 0) {
throw new Negative();
}
}
}
catch(Negative n) {
System.out.println("Any one or more of your command line arg
is negative");
}
}
}

Dr. Purvi Ramanuj


Example 4
• Create custom exception which is thrown if
the value passed is greater than 10.

Dr. Purvi Ramanuj


class MyException extends Exception { public static void
int id;
main(String args[]) {
public MyException(int x) {
id = x;
} try {
public String toString() { compute(5);
return "CustomException[" + id + "]";
}
compute(12);
} } catch(MyException
public class Sampleee { ex1) {
static void compute(int a) throws MyException {
if (a > 10)
throw new MyException(a); System.out.println(ex1);
System.out.println("No error in prog. no
exception caught"); }
} }
}
Dr. Purvi Ramanuj
Dr. Purvi Ramanuj
Example 5
• Create a custom exception which checks the
age >17

Dr. Purvi Ramanuj


class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{

static void validate(int age)throws InvalidAgeException{


if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}

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


}
}
Dr. Purvi Ramanuj
• Output:Exception occured:
InvalidAgeException:not valid rest of the
code...

Dr. Purvi Ramanuj


Find Output Example 6
class MyException extends Exception{
String str1;
/* Constructor of custom exception class here I am copying the message that we are passing while throwing the exception to a
string and then displaying that string along with the message.
*/
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");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
Dr. Purvi Ramanuj
Starting of try block
Catch Block
MyException Occurred: This is My error
Message

Dr. Purvi Ramanuj


Example 7
• Write a program that accepts the fully
qualified name of a class as its argument.
Compute and display how many super classes
exist for that class.If a
ClassNotFoundException occurs, catch it and
provide an error message for the user.

Dr. Purvi Ramanuj


class pb5 {
public static void main(String s[]) {
try {
int count = countSuperclasses(s[0]);
System.out.println(count);
}
catch(ClassNotFoundException e) {
System.out.println("Class not found");
}
catch(Exception e) {
System.out.println("Specify class name as argument");
}
}
static int countSuperclasses(String classname)throws ClassNotFoundException {
Class cls = Class.forName(classname);
int count = 0;
while ((cls = cls.getSuperclass()) != null) {
++count;
}
return count;
}
}

Dr. Purvi Ramanuj


Example 8
• A marklist containing reg.no and marks for a
subject is given. if the marks are <0,user-
defined IllegalMarkException is thrown out
and handled with the message “Illegal Mark”.
For all valid marks, the candidate will be
declared as “PASS” if the marks are equal to or
greater than 40,otherwise it will be declared
as “FAIL”. Write a class called
IllegalMarkException.
Dr. Purvi Ramanuj
class IllegalMarkException extends Exception {
IllegalMarkException() {

}
}
class pb6 {
public static void main(String args[]) {
int p=0,q=0,r=0;

try{
for(int i=0;i<args.length;i++) {
if(Integer.parseInt(args[i])>=40) {
p++;
}

else if(Integer.parseInt(args[i])<0) {
q++;
throw new IllegalMarkException();
}

}
}
catch(IllegalMarkException j) {
System.out.println("Illegal Mark");
}

if(p==args.length && p!=0)


System.out.println("Pass");

else if(p<args.length && p!=0 && q==0)


System.out.println("Fail");
}
}
Dr. Purvi Ramanuj
Thank you

Dr. Purvi Ramanuj

You might also like