0% found this document useful (0 votes)
59 views

What Is Exception: Throwable

The document discusses exception handling in Java. It defines that an exception is a runtime error and occurs due to problems like dividing by zero. It explains the different types of errors like compile-time errors and runtime errors. It describes the syntax of try, catch, throw and finally keywords used in exception handling. It provides examples to demonstrate how to catch and handle exceptions in Java programs.

Uploaded by

DrDinesh Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

What Is Exception: Throwable

The document discusses exception handling in Java. It defines that an exception is a runtime error and occurs due to problems like dividing by zero. It explains the different types of errors like compile-time errors and runtime errors. It describes the syntax of try, catch, throw and finally keywords used in exception handling. It provides examples to demonstrate how to catch and handle exceptions in Java programs.

Uploaded by

DrDinesh Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31

Exception Handling

• What is Exception

• Exception and Error

Throwable

Exception Error
EXCEPTION HANDLING
• It is common to make mistakes while developing as well as
typing a program.
• A mistake might lead to an error causing the program to
produce unexpected results.
• Errors are the wrong that can make a program go wrong.
• An error may produce an incorrect output or may terminate
the execution of the program abruptly or even may cause
the system to crash.
• It is therefore important to detect and manage properly all
the possible error conditions in the program so that the
program will not terminate or crash during execution.
• There are two types of errors:

Compile-time errors
Run-time errors
Compile-time errors:
• The compile-time errors are detected and
displayed by the Java compiler, during the
compilation of the program.

• If a program contains compile-time errors, the


compiler does not create the .class file.

• So, it is necessary to fix all the errors.

• After fixing the errors, the program has to be


recompiled.
Run-time errors:
• Sometimes, a program may compile successfully
creating the .class file but may not run properly.

• Such programs may produce wrong results due to


wrong logic or may terminate due to errors such
as stack overflow.

• Such errors are called as the run-time errors.

• Exception is an abnormal condition that arises in


a code sequence at run time.

• In other words, an exception is a run-time error.


Some of the common exceptions are:
• Dividing an integer by zero.

• Accessing an element that is out of the bounds of an array.

• Trying to store a value into an array of an incompatible class or type

• Trying to cast an instance of a class to one of its subclasses.

• Passing a parameter that is not in a valid range or value for a


method.

• Attempting to use a negative size for an array.

• Accessing a character that is out of bounds of a string.

• Converting invalid string to a number.


Example:
// This program illustrates the run-time errors
class Error_Runtime
{
public static void main(String args[ ])
{
int i = 10 ;
int j = 2 ;
int k = i/(j-j); // Division by zero
System.out.println("\n k = " + k);
int l = i/(j+j);
System.out.println("\n l = " + l);
}
}

The above program is syntactically correct and therefore does not


produce any error during compilation.

However, when the program is run, it displays the following message


and stops without executing further statements.

Division by zero
Exceptions
• An exception is a run-time error.
• When the Java interpreter encounters an error such as dividing
an integer by zero, it creates an exception object and throws it
(informs that an error has occurred).
• If the exception object is not caught and handled properly, the
interpreter will display an error message and will terminate the
program.
• If one wants the program to continue with the execution of the
remaining code, then one should try to catch the exception object
thrown by the error condition and then display an appropriate
message for taking corrective action. The task is known as
exception handling.
• The purpose of exception handling mechanism is to provide a
means to detect and report an exceptional circumstance so that
appropriate action can be taken.
• Java exception handling is managed via five keywords: try,
catch, throw, throws and finally.
• The error handling code basically consists of two segments; one
to detect errors and to throw exceptions and the other to catch
exceptions and to take appropriate actions.
Java Exceptions: Some of the common exceptions are listed
in the following table:
Exception Meaning
ArithmeticException Arithmetic error, such as divide by zero.
ArrayIndexOutOfBoundsException Array index is out of bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
FileNotFoundException Attempt to access a nonexistent file.
IOException Caused by general I/O failures, such as
inability to read from a file.
NullPointerException Caused by referencing a null object
NumberFormatException Caused when a conversion between
strings and number fails.
OutOfMemoryException Caused when there is not enough
memory to allocate a new object
StringIndexOutOfBoundsException Caused when a program attempts to
access a nonexistent character
position in a string.
SerurityException Caused when an applet tries to perform an
action not allowed by the browser’s
security setting.
StackOverflowException Caused when the system runs out of the
stack space.
Syntax of Exception Handling Code: The basic concept of
exception handling is throwing an exception and catching it.

Exception handling mechanism


try block

Statement that causes an


exception
Throws exception
object Exception object creator

catch block

Statement that handles the


exception
Cont.
• Java uses a keyword try to preface a block of code that is likely to cause an error
condition and throw an exception.

• A catch block defined by the keyword catch catches the exception thrown by the
try block and handles it appropriately.

• The catch block is added immediately after the try block.

• The general form of exception handling block is:


try
{
// Block of code to monitor for errors
}
catch(Exception-type1 exOb)
{ // Exception handler for Exception Type1}
catch(Exception-type2 exOb)
{ // Exception handler for Exception Type2}
…………….
…………….
finally
{ // Block of code to be executed before try block ends }

• Here, Exception-type is the type of exception that has occurred.


Now consider the following program, that illustrates the use
of the try and catch to handle exception.
// This program illustrates the use of the try and catch for exception handling
class TryCatch
{
public static void main(String args[ ])
{
int i = 10 ;
int j = 2 ;
int k, l ;
try
{
k = i / ( j – j ); // Exception
}
catch(ArithmeticException e) // Exception will be caught here
{
System.out.println("\n Division by zero");
}
l = i/(j+j);
System.out.println (" l = " + l);
}
}
Cont.
• The above program displays the following output:
• Division by zero
• l =2

• Note that the above program didn’t stop at the point of


exceptional condition.

• It catches the error condition, prints the error message,


and then continues the execution, as if nothing has
happened.

• Notice that the previous program did not display the


value of l.
Now, consider an another program of exception handling in which the try….catch
block catches the invalid entries in the list of the command line arguments.
class Number_Format_Exception
{
public static void main(String args[])
{
int invalid = 0;
int n, count = 0;
for(int i = 0; i < args.length; i++)
{
try
{
n = Integer.parseInt(args[i]);
}
catch (NumberFormatException e)
{
invalid = invalid + 1 ;
System.out.println("\n Invalid Number: " + args[i]);

}
count = count + 1 ;
}
System.out.println("\n Valid Numbers = " + count);
System.out.println("\n Invalid Numbers = " + invalid);
}
}
javac Number_Format_Exception.java
java Number_Format_Exception 10 10.75 50 C++ 50.5 15

Output:
Invalid Number: 10.75
Invalid Number: C++
Invalid Number: 50.5
Valid Numbers = 3
Invalid Numbers = 3
Multiple catch statements:
• It is also possible to have more than one catch statement
in the catch block.
• When an exception in a try block is generated, the Java
treats the multiple catch statements like cases in a switch
statement.
• The first statement whose parameter matches with the
exception object will be executed, and the remaining
statements will be skipped.
• Note that Java does not require any processing of the
exception at all. One can simply have a catch statement
with an empty block to avoid abortion, as shown below:
catch (Exception e) ;
• The catch statement simply ends with a semicolon, which
does nothing. This statement will catch an exception and
then ignore it.
Example:
// This program illustrates the use of the multiple catch statements
class Multiple_Catch
{
public static void main(String args[])
{
try
{
int a = args.length ;
System.out.println(" a = " + a);
int b = 42 / a ;
int c[ ] = {1};
c[42] = 99 ;
}
catch(ArithmeticException e)
{ System.out.println("\n Divide by zero " + e); }
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(" Array index out of bounds " + e);
}
System.out.println(" After the try/catch blocks");
}
}
Use of the finally statement:

• finally statement is used to handle an exception


that is not caught by any of the previous catch
statements.
• finally block can be used to handle any exception
generated within a try block.
• It may be added immediately after the try block or
after the last catch block.
• When a finally block is defined, this is guaranteed
to execute, regardless of whether or not an
exception is thrown.
• The following program illustrates the use of the
finally statement.
Example:
// This program illustrates the use of the multiple catch statements
class Finally_Class
{ // Throwing an exception out of the method
static void method1( )
{
try
{
System.out.println("\n Inside method1");
throw new RuntimeException("Example");
}
finally
{ System.out.println("\tfinally block of method1"); }
}
// Return from within a try block
static void method2( )
{
try
{
System.out.println("\n Inside method2");
return ;
}
finally
{ System.out.println("\tfinally block of method2"); }
}
Cont.
// Execute the try block normally
static void method3( )
{
try
{
System.out.println("\n Inside method3");
}
finally
{
System.out.println("\tfinally block of method3");
}
}
public static void main(String args[])
{
try
{
method1( );
}
catch(Exception e)
{
System.out.println("\tException caught");
}
method2( );
method3( );
}
} // End of the class definition
Output:
Inside method1
finally block of method1
Exception caught
Inside method2
finally block of method2
Inside method3
finally block of method3
Cont.
• In above program, method1( ) prematurely breaks out of
the try by throwing an exception.

• The finally clause is executed on the way out.

• The method2( ) of try statement is exited via a return


statement.

• The finally clause is executed before method2 returns.

• In the method3( ), the try statement executes normally,


without error.

• However, the finally block is still executed.


Throwing own exception:

• It is also possible to throw our own exceptions.


This can be done by using the keyword throw as
follows:

throw new Throwable_subclass ;

• For example:
throw new ArithmeticException( );
throw new NumberFormatException( );
Example: Program to illustrate the use of throwing an exception
import java.lang.Exception ;
class MyException extends Exception
{
MyException(String message)
{ super(message) ; }
}
class User_Exception
{
public static void main(String args[])
{
int x = 5, y= 1000 ;
try
{
float z = (float)x / (float)y ;
if(z < 0.01)
{
throw new MyException(" Number is too small");
}
}
catch(MyException e)
{
System.out.println("\n Caught my exception");
System.out.println( e.getMessage( ) );
}
finally
{ System.out.println(" I am always here"); }
}
}
Cont.

• In the above program, Exception is a subclass of Throwable and


therefore MyException is a subclass of Throwable class.

• An object of a class that extends Throwable can be thrown and


caught.
Difference between Throws and
Throw
• We already know we can handle exceptions using try-
catch block.
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
}
}
Cont..
• 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.
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
}}
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);
}}}
Cont..
• 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.
Throw Throws

Used with method (or constructor)


Used within a method (or constructor)
signature

Used to throw an exception explicitly Used to declare exceptions

Can only throw a single exception Can declare multiple exceptions

Followed by a throwable instance Followed by an exception class name

Cannot be used to propagate checked Can be used to propagate checked


exceptions by itself exceptions by itself

You might also like