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

Chapter 7 Exception Handling

Uploaded by

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

Chapter 7 Exception Handling

Uploaded by

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

EXCEPTION HANDLING

IN JAVA
Table of Contents
• Exception Handling Fundamentals
• Exception Types
• Uncaught Exception
• Using Try-Catch
• Multiple Catch Clauses
• Nested Try Statement
• Throw
• Throws
• Finally.
Introduction
• Error are the wrongs that make program go wrong.
• Error may produce an incorrect output or terminate program execution
abruptly or abnormally.
• Types of error:
• Compile Time Error: All Syntax related error. Eg: Missinf Semicolon,
undeclared variable, missing braces, etc.
• Run Time Error: Successfully creates a .class file but not run properly, as
a result, produces wrong result or may terminate abnormally. Eg: Divide by
zero, Accessing element out of bound, etc.
• Illustration of run time error, eg:
Class Error2
{ p.s.v.m(…..)
{ int a=10, b=5, c=5;
int x= a/(b-c); //Div. by Zero
SOP(“X= ”+X);
}
}
Error: java.lang.ArithmeticException: / by zero at Error2.main
• An Exception is a condition caused by run time error in a program. (It
leads to abnormal termination of program)
• Sample Program:
statement 1;
statement 2; //exception occurs
statement 3;
statement 4;
Then rest of the code (3-4) will not be executed.

• If we want to continue program execution with remaining code, then we


should catch exception object thrown by errorneous statement and display
appropriate message for corrective action. (Exception Handling)

• Advantage of Exception Handling: To maintain the normal flow of the


application

• Exception Handling Mechanism:


– Hit (Find problem)
– Throw ( Inform occurrence of error)
– Catch (Receive error information)
– Handle (Take corrective action)
Syntax for Exception Handling Code

try Block
Throws
exception Statement that causes an Exception Object
object exception Creator

Catch Block
Statement that handles the Exception Handler
exception

Figure: Exception Handling Mechanism


• Example:
try
{
Throw
Z = X / Y;
}
catch (ArithmeticException e )
{
SOP(“Div. by zero error”);
}
• Type of exception are stored in: java.lang.*
• Eg of common exception:
– 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: Cause by attempt to acces non existing file.
– IOException: Caused by general IO Failure
Example of try-catch program
Class Error3
{ p.s.v.m(…..)
{ int a=10, b=5, c=5;
int x, y;

try
{ x= a/(b-c);
}
catch(ArithmeticException e)
{ SOP(“Div. By Zero…”); }

y = a / (b+c);
SOP(“Y = ” + Y);
}
}
Example of multiple catch blocks
Class error4
{ p.s.v.m(String args[])
{ int a[]={5,10}; int b= 5;
try
{ int x= a[1] / (b-a[0]); }
Output:
Div by Zero
catch (ArithmeticException e) Y=2
{ SOP(“Div. by Zero”); }

catch (ArrayIndexOutOfBoundException e)
{ SOP(“Array Index Error”); }

catch (ArrayStoreException e)
{ SOP(“Wrong Data Type”); }
int y= a[1] / a[0]; SOP(“Y = ” + y);
}
}NOTE: if exception not handled by code int y= a[1] / a[0] ;SOP(“Y = ” +
y); will not execute.
Example of Nested try statements
Class eg_nested_try
{ p.s.v.m(String args[])
{
try
{ int a=2, b=4, c=2, x=7, z;
int p[ ]= { 2 };
p[ 3 ]= 33;
try
{ z = x / ( (b*b)- (4 * a*c) ) ;
SOP(“Value z= “ + z);
}
catch( ArithmeticException e)
{ SOP(“Div. by Zero in Arithmetic Expression”); }
}
catch ( ArrayIndexOutOfBoundsException e)
{ SOP(“Array Index Out of Bound”); }
}
}
Java finally block
• Java finally block is a block that is used to
execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether
exception is handled or not.
Java finally block
General form of exception-handling block
try
{ // block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{ // exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{ // exception handler for ExceptionType2
}
// ...
finally
{// block of code to be executed after try block ends
}
Finally block
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...");
} Output:
} finally block is always executed
Exception in thread main java.lang.ArithmeticException:/
by zero
throw clause(Un checked)
• The Java throw keyword is used to explicitly throw an
exception.
• We can throw either checked or uncheked exception in java
by throw keyword. The throw keyword is mainly used to
throw custom exception. We will see custom exceptions later.
• Syntax:
– throw exception object;
– Example:
• throw new IOException("sorry device error);

Exception Object
throw clause example
public class TestThrow1{
static void validate(int age){
try{
if(age<18)
throw new ArithmeticException("not valid");
else
Exception
System.out.println("welcome to vote");
created by our
} catch(ArithmeticException e){ sop(e);} program and
} thrown.

public static void main(String args[]){

validate(13);

}
Output:
}
Exception in thread main java.lang.ArithmeticException:not valid
throws clause (Checked)
• The 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 normal flow can be
maintained.
• Syntax:
return_type method_name() throws exception_class_name{
//method code
}
throws clause
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
Output:
}
} exception handled
public class Testthrows2{ normal flow...
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...");
}
}
Difference between throw and throws
throw throws
Java throw keyword is used to Java throws keyword is used to declare an
explicitly throw an exception. exception.

Checked exception cannot be Checked exception can be propagated with


propagated using throw only. throws.

Throw is followed by an instance. Throws is followed by class.

Throw is used within the method. Throws is used with the method signature.

You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
User-defined exception
• Extending predefined Exception class to create
your own Exception.
• Syntax: throw new Throwable Subclass();
• Hierarchy:
Example of User Defined/own/ custom Exception

class MyException extends Exception


{ MyException(String msg) Own Exception
{ Super(msg); MyException
}
}
class MyException_Demo
{ p.s.v.m(….)
{ int x=10; int y=20;
if(x<y)
{ throw new MyException (“x<y is wrong”);
}
catch (MyException e)
{ SOP( e.getMessage() ); OUT PUT:
x<y is wrong
}
}
}
Example of Throwing Own Exception
Import java.lang.Exception;
Class MyException extends Exception
{ MyException(String msg)
{ Super(msg); }
}
class Test_My_Exception
{ p.s.v.m(String args[] )
{ int x= 5, y= 1000;
try
{ float z= (float) x / (float) y ;
if (z < 0.01)
{ throw new MyException(“Small Num.”) }
}
catch (MyException e)
{ SOP(“ Caught My Exception ”);
SOP(e.getMessage() );
}
}
}
Summary
• The exception handling in java is one of the powerful mechanism to
handle the runtime errors so that normal flow of the application can be
maintained.

• Meaning: Exception is an abnormal condition.

• Java exception is an object that describes an exceptional (error)


condition that has occurred in a piece of code.

• When an exceptional occurs, an object representing that exception is


created and thrown in the method that caused the error.

• Exceptions can be generated by the Java run-time system, or they can


be manually generated by your code.

• Exception Handling is a mechanism to handle runtime errors such as


ClassNotFound, IO, SQL, Remote etc.
• Java exception handling is managed by: try, catch, throw, throws, and
finally.

• Program statements that you want to monitor for exceptions are


contained within a try block.

• If an exception occurs within the try block, it is thrown. Your code can
catch this exception (using catch) and handle it in some rational manner.

• System-generated exceptions are automatically thrown by the Java run-


time system. To manually throw an exception, use the keyword throw.

• Any exception that is thrown out of a method must be specified by a


throws clause.

• Any code that absolutely must be executed after a try block completes is
put in a finally block.

You might also like