0% found this document useful (0 votes)
9 views26 pages

Java Exception Handling Explained

The document discusses exception handling in programming, explaining the difference between checked and unchecked exceptions, and the importance of using try-catch blocks to manage abnormal events during program execution. It also covers the use of 'throws' and 'throw' keywords for exception declaration and generation, as well as the concept of user-defined exceptions and the role of 'finally' blocks in ensuring certain code executes regardless of exceptions. Overall, it emphasizes the necessity of proper exception handling to maintain program stability and prevent resource leaks.

Uploaded by

anantmishra2006
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)
9 views26 pages

Java Exception Handling Explained

The document discusses exception handling in programming, explaining the difference between checked and unchecked exceptions, and the importance of using try-catch blocks to manage abnormal events during program execution. It also covers the use of 'throws' and 'throw' keywords for exception declaration and generation, as well as the concept of user-defined exceptions and the role of 'finally' blocks in ensuring certain code executes regardless of exceptions. Overall, it emphasizes the necessity of proper exception handling to maintain program stability and prevent resource leaks.

Uploaded by

anantmishra2006
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

Exception Handling

Error
Can not be handled by Programmer
Example
Not enough space
LOW Memory
NO OS Support
Lack of h/w Support
Stack Overflow
Exception
An exception is an abnormal event that arises
during the execution of the program and
disrupts the normal flow of the program.
“Handling”
“what happens after an abnormality occurred?“
Is actually important.
If these exceptions are not handled properly, the
program terminates abruptly and may cause
severe consequences. For example, the network
connections, database connections and files
may remain opened; database and file records
may be left in an inconsistent state.
“Handling”
Suppose there are 10 statements in your
program and there occurs an exception at
statement 5, the rest of the code will not be
executed i.e. statement 6 to 10 will not be
executed. If we perform exception handling, the
rest of the statement will be executed. That is
why we use exception handling in Java.
Checked Exception
Checked exception is an exception due to an error
situation that can be foreseen by the programmer
A checked exception must be handled by the using
try-catch block or at least by using throws clause
with that method. Non Compliance of this rule
result in a compile time error.
For example: FileNotFoundException, SQLException
Unchecked Exception
• Class RuntimeException and all its subclasses
are unchecked exception.
• An unchecked exception is an exception which
could have been avoided by the programmer.
• If there is a chance of unchecked exception
than it is ignored by the compiler.
For example NumberFormatException,
NullPointerException,IndexOutOfBoundsExcepti
on etc.
“try-catch” block
• A part of the code that can generate exception should
be kept inside try block, and exception should be
handled in the catch block;
• The corrective action in case of an exception should be
put in the catch block.
• However a single block of code can raise more than
one exception
• We can specify two or more catch clauses followed by
try block
• Catch clauses are executed in order occurrence. If one
is executed(After match) others are bypassed and the
execution after try catch blocks starts.
“try-catch” block
• In case of using multiple catch clauses, the sub
class Exception must come before super class.
• This is done because if super class Exception
comes first than catch block having sub class
will be unreachable. This will apparently
manifest unreachable code error.
public class Demo7 {
public static void OUTPUT:
main(String...strings) {
[Link]("First Line"); First Line
int x=12; -6
for(int i=-2;i<5;i++) -12
{ Don divide by zero
try { 12
[Link](x/i); 6
} 4
catch (ArithmeticException e) 3
{ Last Line
[Link](" Don divide
by zero");
}
}
[Link]("Last Line");
}
}
multiple catch clauses
public class Demo {
public static void main(String[] args)
{
[Link]("Fisrt line");
try{ OUTPUT:
[Link](12/0);
String str="HELLO"; Fisrt line
[Link]([Link](10)); dont /by zero
} last line
catch(ArithmeticException ae)
{
[Link]("dont /by zero");
}
catch (StringIndexOutOfBoundsException
e) {
[Link]("Sring Exception");
}
[Link]("last line");
}
}
Nested “try-catch” block
• Try statement can be nested.
• If inner try bock doesn't have a catch block
than catch block of outer try block will handle
the exception
• This continues until one catch block doesn’t
handle the Exception or till all the try blocks
are exhausted
• If no catch matches than java runtime handles
the exception
public class Demo4 {
public static void main(String[] args) {
[Link]("First Line");
int x=12;String name=null;
try {
[Link]("inside outer try block");
[Link](x/5);
try {
[Link]("inside inner try block");
[Link]([Link]());
}catch (NullPointerException e) {
[Link]("Null pointer");
}
}catch (ArithmeticException e) {
[Link]("Don't divide by zero");
}
[Link]("Last Line"); OUTPUT:
} First Line
} inside outer try block
2
inside inner try block
Null pointer
Last Line
“throws”
• Sometimes a method may cause an exception but
does not seek to handle it.
• This method must specify this behaviour so that
callers of this methods may protect themselves
against that Exception.
• While declaring such method programmer have
to specify which exception this method may
throw using “throws” keyword.
• Multiple Exceptions may be added using comma
separated list
public class ThrowsDemo {

public void testThrows() throws IOException


{
FileOutputStream fos=new FileOutputStream("[Link]");
String str="welcome to exception handling";
byte[] b=[Link]();
[Link](b);
[Link]("Written to file successfully");
[Link]();
}
} public static void main(String[] arg)
{
ThrowsDemo td=new ThrowsDemo();
try {
[Link]();
} catch (IOException e) {
[Link]("Could not write to the
file");
}
}
Rule of Throws(Overriding method)
• The overriding method must NOT throw checked
Exceptions those are new or broader than those
declared by the overridden method.
• For example: A method a method throwing
SQLException can be overridden by a method throwing
IOException or ANY other Exception unless the
Exception is subclass of SQLException class.
• Or A method declared in Super class A throwing
Exception X , if overridden in Sub class B can only
throw either X as Exception or Any Exception Sub class
of X.
• This rule is applicable only for checked Exceptions
public class A {
public void test() throws
FileNotFoundException
{
FileInputStream fis=new
FileInputStream("[Link]");
}
}

public class B extends A{

public void test() throws IOException


{
FileInputStream fis=new
FileInputStream("[Link]");
}
}
“Throw”
• System generated Exceptions are thrown
Automatically. However, sometimes you may
also yield to throw Exception explicitly. This
can be done using “throw” keyword.
• Syntax:
throw ThrowableInstance
Here ThrowableInstance must be object of
Throwable or its subclass
public class ThrowDemo {

public void test()


{
[Link]("in Test Method");
throw new ArithmeticException(); Output:
} in Test Method
Exception in thread "main"
} [Link]
at
[Link]([Link])
public class DemoThrow { at
[Link]([Link])
public static void main(String[] args) {
ThrowDemo td=new ThrowDemo();
[Link]();
[Link]("main method");
}

}
import [Link];
import [Link];

public class DEMO12 {


public static void main(String[] args) {
Scanner scan = new Scanner([Link]);
[Link]("Enter a number");
int k = [Link]();
if (k < 0) {
throw new ArithmeticException();
} else if (k >= 0) {
throw new ArrayIndexOutOfBoundsException();
} else {
[Link]("your number is
correct:" + k); Enter a number
} 12
} Exception in thread "main"
} [Link]
xception
at [Link]([Link])
“User defined Exceptions”
• Apart from rich set of built-in Exceptions, JAVA
provide the ability to user to define Their Own
Exception classes.
• For example: if we want minimum amount to be
filled before starting a bank credit or debit
transaction.
• All user defined Exceptions must be subclasses of
Exception class or its sub classes.
• To display meaningful information, user need to
override the toString() method.
import [Link];
class UserDefinedExcepton extends Exception {
@Override
public String toString() {
return "Wrong Amount Entered";
}
}
public class DEMO12 {
public static void main(String arg[]) throws
UserDefinedExcepton {
[Link]("Enter amoung to withdraw");
Scanner scan = new Scanner([Link]);
int k = [Link]();
if (k < 100) {
throw new UserDefinedExcepton();
} else {
[Link]("Your account is debited Rs " +
k);
}
Enter amoung to withdraw
}
12
}
Exception in thread "main" Wrong Amount
Entered
at [Link]([Link])
“finally”
An exception can force a program to follow a non
linear path and it can bypass few statements.
For example a connection with database is opened
and then some exception occurs.
The program will terminate eventually, and
connection will still remain open.
Finally block can be used to close the connection.
Finally block guarantees that the statement will be
executed in all circumstances
import [Link];
public class DEMO12 {
public static void main(String arg[]) throws
FileNotFoundException {
[Link]("Welcome");
try {
[Link]("inside try before exception");
throw new FileNotFoundException();
}
finally
{
[Link]("inside finally");
}
}
}

Welcome
inside try before exception
inside finally
Exception in thread "main"
[Link]
at [Link]([Link])
import [Link];
public class DEMO12 {
public static void main(String arg[]) {
[Link]("Welcome");
try {
[Link]("inside try before
exception");
throw new FileNotFoundException();
} catch (FileNotFoundException e) {
[Link]();
} finally {
[Link]("inside finally");
}
}
}
Welcome
inside try before exception
[Link]
at [Link]([Link])
inside finally

You might also like