0% found this document useful (0 votes)
106 views14 pages

FAL (2019-20) CSE2005 ETH 302 AP2019201000577 Reference Material I Exception in Java

The document discusses Java exception handling keywords like try, catch, finally, throw and throws. It provides descriptions of what each keyword is used for. For example, try is used to specify code that might throw exceptions, catch handles any exceptions in the try block, finally always executes. throw is used to explicitly throw an exception while throws declares exceptions a method may throw but not throw them. The document also provides examples of using these keywords to handle exceptions.

Uploaded by

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

FAL (2019-20) CSE2005 ETH 302 AP2019201000577 Reference Material I Exception in Java

The document discusses Java exception handling keywords like try, catch, finally, throw and throws. It provides descriptions of what each keyword is used for. For example, try is used to specify code that might throw exceptions, catch handles any exceptions in the try block, finally always executes. throw is used to explicitly throw an exception while throws declares exceptions a method may throw but not throw them. The document also provides examples of using these keywords to handle exceptions.

Uploaded by

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

Java Exception Keywords

There are 5 keywords which are used in handling


exceptions in Java.
Keyword Description
The "try" keyword is used to specify a block
where we should place exception code. The
Try
try block must be followed by either catch or
finally. It means, we can't use try block alone.
The "catch" block is used to handle the
exception. It must be preceded by try block
catch
which means we can't use catch block alone.
It can be followed by finally block later.
The "finally" block is used to execute the
finally important code of the program. It is executed
whether an exception is handled or not.
The "throw" keyword is used to throw an
throw
exception.
The "throws" keyword is used to declare
exceptions. It doesn't throw an exception. It
throws specifies that there may occur an exception in
the method. It is always used with method
signature.
Catching Exceptions
A method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed
around the code that might generate an exception. Code
within a try/catch block is referred to as protected code,
and the syntax for using try/catch looks like the
following −
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
The code which is prone to exceptions is placed in the
try block. When an exception occurs, that exception
occurred is handled by catch block associated with it.
Every try block should be immediately followed either
by a catch block or finally block.
A catch statement involves declaring the type of
exception you are trying to catch. If an exception occurs
in protected code, the catch block (or blocks) that
follows the try is checked. If the type of exception that
occurred is listed in a catch block, the exception is
passed to the catch block much as an argument is
passed into a method parameter.
Example
The following is an array declared with 2 elements.
Then the code tries to access the 3rd element of the array
which throws an exception.
File Name : ExcepTest.java
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]);
System.out.println("Exception”);
}
Catch(ArrayIndexOutOfBoundsException
e) {
System.out.println("Exception thrown
:" + e);
}
System.out.println("Out of the
block");
}
}
This will produce the following result −
Output
Exception thrown
:java.lang.ArrayIndexOutOfBoundsExcep
tion: 3
Out of the block
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;

System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format
exception");
}
}
}

Output:

Number format exception

Multiple Catch Blocks


A try block can be followed by multiple catch blocks.
The syntax for multiple catch blocks looks like the
following −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
The previous statements demonstrate three catch
blocks, but you can have any number of them after a
single try. If an exception occurs in the protected code,
the exception is thrown to the first catch block in the
list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the
exception passes down to the second catch statement.
This continues until the exception either is caught or
falls through all catches, in which case the current
method stops execution and the exception is thrown
down to the previous method on the call stack.
Example
Here is code segment showing how to use multiple
try/catch statements.
class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[10]=10/5;
System.out.println("Last Statement of try
block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a
number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements
outside of the limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
System.out.println("Out of the try-catch
block");
}
}

Output:

Accessing array elements outside of the limit


Out of the try-catch block

try {
file=new
FileInputStream(fileName);
x = (byte) file.read();
} catch (IOException i) {
i.printStackTrace();
return -1;} catch
(FileNotFoundException f) // Not
valid! {
f.printStackTrace();
return -1;
}

Syntax of Nested try Catch


....
//Main try block
try {
statement 1;
statement 2;
//try-catch block inside another try block
try {
statement 3;
statement 4;
//try-catch block inside nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2) {
//Exception Message
}
}
catch(Exception e1) {
//Exception Message
}

}
//Catch of Main(parent) try block
catch(Exception e3) {
//Exception Message
}
Example
class NestingDemo{
public static void main(String args[]){
//main try-block
try{
//try-block2
try{
//try-block3
try{
int arr[]= {1,2,3,4};
/* I'm trying to display the value of
* an element which doesn't exist.
The
* code should throw an exception
*/
System.out.println(arr[10]);
}catch(ArithmeticException e){
System.out.print("Arithmetic
Exception");
System.out.println(" handled in try-
block3");
}
}
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-
block2");
}
}
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-
block");
}
catch(ArrayIndexOutOfBoundsException e4){

System.out.print("ArrayIndexOutOfBoundsException
");
System.out.println(" handled in main try-
block");
}
catch(Exception e5){
System.out.print("Exception");
System.out.println(" handled in main try-
block");
}
}
}

Output:

ArrayIndexOutOfBoundsException handled in main try-block

As you can see that the ArrayIndexOutOfBoundsException occurred in the grand


child try-block3. Since try-block3 is not handling this exception, the control then gets
transferred to the parent try-block2 and looked for the catch handlers in try-block2. Since
the try-block2 is also not handling that exception, the control gets transferred to the main
(grand parent) try-block where it found the appropriate catch block for exception. This is
how the nesting structure works.

Throw vs Throws in java


1. Throws clause is used to declare an exception, which means it
works similar to the try-catch block. On the other hand throw
keyword is used to throw an exception explicitly.

2. If we see syntax wise than throw is followed by an instance of


Exception class and throws is followed by exception class names.
For example:
throw new ArithmeticException("Arithmetic
Exception");

and
throws ArithmeticException;

3. Throw keyword is used in the method body to throw an


exception, while throws is used in method signature to declare the
exceptions that can occur in the statements present in the method.
For example:
Throw:

...
void myMethod() {
try {
//throwing arithmetic exception using throw
throw new ArithmeticException("Something went
wrong!!");
}
catch (Exception exp) {
System.out.println("Error: "+exp.getMessage());
}
}
...

Throws:

...
//Declaring arithmetic exception using throws
void sample() throws ArithmeticException{
//Statements
}
...

4. You can throw one exception at a time but you can handle multiple
exceptions by declaring them using throws keyword.
For example:
Throw:

void myMethod() {
//Throwing single exception using throw
throw new ArithmeticException("An integer should
not be divided by zero!!");
}
..

Throws:

//Declaring multiple exceptions using throws


void myMethod() throws ArithmeticException,
NullPointerException{
//Statements where exception might occur
}

These were the main differences between throw and throws in Java.

Throw Example

Create your own exception by extending exception class and throw your
own exception using throw clause

public class Example1{


void checkAge(int age){
if(age<18)
throw newArithmeticException("Not Eligible
for voting");
else
System.out.println("Eligible for voting");
}
public static void main(String args[]){
Example1 obj = new Example1();
obj.checkAge(13);
System.out.println("End Of Program");
}
}

Output:

Exception in thread "main"


java.lang.ArithmeticException:
Not Eligible for voting
at Example1.checkAge(Example1.java:4)
at Example1.main(Example1.java:10)

Throws Example

-if a method has no exception handling mechanism within that method it


might throw the exception

-caller of the method is intimated explicitly that certain types of exception


could be expected from the method and caller must catch it

-Throws clause is used for that

-specified immediately after the method declaration statement and just


before the opening brace

public class Example1{


int division(int a, int b) throws
ArithmeticException{
int t = a/b;
return t;
}
public static void main(String args[]){
Example1 obj = new Example1();
try{
System.out.println(obj.division(15,0));
}
catch(ArithmeticException e){
System.out.println("You shouldn't divide
number by zero");
}
}
}

Output:

You shouldn't divide number by zero


The Throws/Throw Keywords
If a method does not handle a checked exception, the
method must declare it using the throws keyword.
 The throws keyword appears at the end of a
method's signature.
You can throw an exception, either a newly instantiated
one or an exception that you just caught, by using the
throw keyword.
Try to understand the difference between throws and
throw keywords, throws is used to postpone the
handling of a checked exception and throw is used to
invoke an exception explicitly.
throw
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

User-defined Exceptions
You can create your own exceptions in Java. Keep the
following points in mind when writing your own
exception classes −
 All exceptions must be a child of Throwable.

 If you want to write a checked exception that is

automatically enforced by the Handle or Declare


Rule, you need to extend the Exception class.
 If you want to write a runtime exception, you need

to extend the RuntimeException class.


class JavaException{
public static void main(String args[]){
try{
throw new MyException(2);
// throw is used to create a new exception
and throw it.
}
catch(MyException e){
System.out.println(e) ;
}
}
}
class MyException extends Exception{
int a;
MyException(int b) {
a=b;
}
public String toString(){
return ("Exception Number = "+a) ;
}
}

Throws keyword is used for handling checked exceptions . By using


throws we can declare multiple exceptions in one go.
What is the need of having throws keyword when you can handle exception
using try-catch?

The throws does the same thing that try-catch does but there are some
cases where you would prefer throws over try-catch. For example:
Lets say we have a method myMethod() that has statements that can
throw either ArithmeticException or NullPointerException, in this case you
can use try-catch as shown below:

public void myMethod()


{
try {
// Statements that might throw an exception
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}

But suppose you have several such methods that can cause 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.

One way to overcome this problem is by using throws like this: declare the
exceptions in the method signature using throws and handle the exceptions
where you are calling this method by using try-catch.
Another advantage of using this approach is that you will be forced to
handle the exception when you call this method, all the exceptions that are
declared using throws, must be handled where you are calling this method
else you will get compilation error.
public void myMethod() throws ArithmeticException,
NullPointerException
{
// Statements that might throw an exception
}

public static void main(String args[]) {


try {
myMethod();
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}

Example of throws Keyword

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);
}
}
}

Output:

java.io.IOException: IOException Occurred


class Example1{
void method1() throws ArithmeticException{
throw new ArithmeticException("Calculation
error");
}
void method2() throws ArithmeticException{
method1();
}
void method3(){
try{
method2();
}
catch(ArithmeticException e){
System.out.println("ArithmeticException
handled");
}
}
public static void main(String args[]){
Example1 obj=new Example1();
obj.method3();
System.out.println("End Of Program");
}
}

Output:

ArithmeticException handled
End Of Program

When you don’t handle exception and instead declare it at


all the places
The ideal way to use throws is by declaring the exceptions in method signature and handle
the exceptions using try-catch in calling method. Lets see what happens when we declare the
exception at both the places, in method signature as well as in calling method.

class ExceptionExample{
void method()throws ArithmeticException{
throw new ArithmeticException("ArithmeticException
Occurred");
}
}
class Example1{
public static void main(String args[])throws
ArithmeticException{
ExceptionExample obj=new ExceptionExample();
obj.method();

System.out.println("End Of Program");
}
}
Output:

Exception in thread "main" java.lang.ArithmeticException:


ArithmeticException Occurred
at ExceptionExample.method(Example1.java:4)
at Example1.main(Example1.java:10)

You might also like