[go: up one dir, main page]

0% found this document useful (0 votes)
17 views27 pages

Java Exception Handling Explained

The document provides an overview of exception handling in Java, explaining that exceptions disrupt normal program flow and can be categorized into compile-time errors, runtime errors, and logic errors. It details the types of exceptions, including checked and unchecked exceptions, and illustrates how to use try-catch blocks for handling exceptions, as well as the use of finally blocks and the throw and throws keywords. Additionally, it discusses creating custom exceptions and provides examples of common exceptions and their handling in Java code.

Uploaded by

Anurag Yadav
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)
17 views27 pages

Java Exception Handling Explained

The document provides an overview of exception handling in Java, explaining that exceptions disrupt normal program flow and can be categorized into compile-time errors, runtime errors, and logic errors. It details the types of exceptions, including checked and unchecked exceptions, and illustrates how to use try-catch blocks for handling exceptions, as well as the use of finally blocks and the throw and throws keywords. Additionally, it discusses creating custom exceptions and provides examples of common exceptions and their handling in Java code.

Uploaded by

Anurag Yadav
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

Exception Handling

By Ms Ashima Gambhir
Exception Handling

 Exception
 In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
Exception Handling
 Exception Handling is a mechanism to handle runtime errors.
 Normal flow of the application can be maintained.
 It is an object which is thrown at runtime.
 Exception handling done with the exception object.
Types of Errors

 There are three categories of errors:


 Compile Time errors – All the syntax error will be detected and displayed by
the java compiler and therefore these errors are known as compile time error.
Like missing semicolon, missing of identifiers and keywords, use of undeclared
variables etc.
 Runtime errors – Sometimes a program may compile successfully
creating .class file but may not run properly. Run time errors occur while the
program is running if the environment detects an operation that is impossible
to carry out.
Like Dividing an integer by zero, Accessing an element that is out of bound of
an array etc.
 Logic errors - occur when a program doesn't perform the way it was intended
to.
Types of Exceptions

 Types of Exception:
There are mainly two types of exceptions:
 Checked
 Unchecked – Eg. error
 Checked Exception - are checked at compile-time.
 Unchecked Exception - are not checked at compile-time rather they are
checked at runtime.
Types of Exceptions

 Checked Exception – These exceptions are expilicitly handled in the


code itself with the help of try-catch blocks. Checked exception are
extended from [Link] class
 Unchecked Exception – These exceptions are not essentially handled
in the program code, instead JVM handles such exceptions.
Unchecked exceptions are extended from the
[Link] class. Classes that extends
RuntimeException, Error and their subclasses are known as
unchecked exceptions e.g. ArithmeticException,NullPointerException,
ArrayIndexOutOf Bounds Exception etc.
Common Java Exceptions

 Exception Types
1. Arithmetic Exception- Caused by math errors as division by zero
2. ArrayIndexOutOfBoundsException-Caused by bad array indexes.
3. ArrayStoreException-Caused when a program tries to store the wrong
type of data in array.
4. FileNotFoundException-Caused by an attempt to access a nonexistent
file.
5. IOException-Caused by general I/O failure, such as inability to read
from a file.
6. NumberFormatException-Caused when a conversion between strings
and number fails.
try {
// Code which might throw an
exception
}
catch(Exceptionclass object1)
{ // code to handle an exception

Exception }
catch(Exceptionclass object2)
Syntax { // code to handle an exception
}
finally
{
// ALWAYS executed whether an
exception was thrown or not
}
Example

class Simple
{
public static void main(String args[])
{
int data=50/0;
[Link]("rest of the code...");
}}
Output: Exception in thread main [Link]:/ by zero
Rest of the code is not executed (rest of the code..)statement is not
printed.
class Simple1
{
public static void main(String args[])
{
try
{
int data=50/0;
}
Example catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code..."); }
}
Output: Exception in thread main
[Link]:/ by zero rest of
the code…
Multiple Catch Block

Multiple catch block:


 If more than one exception can occur, then we use multiple catch blocks
 When an exception is thrown, each catch statement is inspected in order, and the
first one whose type matches that of the exception is executed
 After one catch statement executes, the others are bypassed
Syntax:try
{ // Code which might throw an exception
}
catch(Exceptionclass object1)
{ // code to handle an exception }
catch(Exceptionclass object2)
{ // code to handle an exception }
Example of Multi Catch Statements

Class MultiCatch catch(ArrayIndexOutOfBoundsException e)


{ {
public static void main(String args[])
[Link](“Array Index error”);
{
}
int a[] = {5,10};
catch(ArrayStoreException e)
int b=5;
try {
{ [Link](“Wrong data type”);
int x = a[2]/b-a[1]; }
} int y = a[1]/a[0];
catch(ArithmeticException e) [Link](“y=“ +y);
{
}
[Link](“Division by zero”);
}
}
 Nested try Statements
A try statement can be inside the
block of another try
Each time a try statement is entered,
the context of that exception is
Nested Try pushed on the stack
If an inner try statement does not
Statements have a catch, then the next try
statement’s catch handlers are
inspected for a match
If a method call within a try block has
try block within it, then then it is still
nested try
Syntax of Nested Try Block
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Program
class Excep6 try
{
{
int a[]=new int[5];
public static void main(String args[])
a[5]=4;
{ }
try catch(ArrayIndexOutOfBoundsException e)

{ {
[Link](e);
try
}
{
[Link]("other statement");
S.o.p("going to divide"); }
int b =39/0; catch(Exception e)

} {
[Link]("handeled");
catch(ArithmeticException e)
}
{ [Link]("normal flow..");
[Link](e); }

} }
Finally Block

 Finally block
 is a block that is always executed.
 To perform some important tasks such as closing connection, stream
etc.
 Used to put "cleanup" code such as closing a file, closing connection
etc.
 Finally creates a block of code that will be executed after a try/catch
block has completed
 Finally block will be executed whether or not an exception is thrown.
 Each try clause requires at least one catch or finally clause.
 Note: Before terminating the program, JVM executes finally block(if
any).
 Note: finally must be followed by try or catch block.
Example of Finally Block
class Simple
{
public static void main(String args[])
{
try {
int data=25/0;
[Link](data);
}
catch(ArithmeticException e)
{
[Link](e);
}
finally {
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}}
Throw keyword

throw keyword
 keyword is used to explictily throw an exception / custom exception.
throw new ExceptionName("Error Message");
 Throw either checked or uncheked exception.
throw new ThrowableInstance
 ThrowableInstance must be an object of type Throwable / subclass
Throwable
 There are two ways to obtain a Throwable objects:
 Using a parameter into a catch clause
 Creating one with the new operator
Example

import [Link].*; throw new


public class Example IllegalArgumentException
{ ("You have entered no"+" "+ x +"
public static void main(String args[]) "+ "which is less than 0");
throws IOException
}
{
DataInputStream dis=new
else
DataInputStream([Link]); {
int x = [Link]([Link]());
[Link]("The no is"+x);
if(x < 0)
}
{
throw new IllegalArgumentException(); }
}
throws

throws
 If a method is capable of causing an exception that it does not handle,
it must specify this behavior so that callers of the method can guard
themselves against that exception
type method-name( parameter-list) throws exception-list
{
// body of method
}
 It is not applicable for Error or RuntimeException, or any of their
subclasses
Throw vs throws

Throw keyword Throws keyword


throw is used to explicitly throw throws is used to declare an
an exception. exception
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


exception You can declare multiple exception
e.g. public void method()throws
IOException,SQLException.
Creating and throwing our own
exception
Import [Link]; If(z<0.01)
Class MyException extends Exception {
{ Throw new MyException(“Number is too small”);

MyException(String message) }

{ }
Catch(MyException e)
Super(message);
{
}
[Link](“caught my exception”);
}
[Link]([Link]);
Class TestMyException
}
{
Finally
Public static void main(String args[])
{
{
[Link](“I am always here”);
Int x=5, y=1000; }
Try }
{ }
Float z= (float)x/(float)y;

You might also like