SlideShare a Scribd company logo
UNIT-III
Exception Handling and I/O
UNIT-III
EXCEPTION HANDLING AND I/O
Exceptions - Exception hierarchy - throwing and
catching exceptions – built-in exceptions, creating
own exceptions, Stack Trace Elements. Input /
Output Basics – Streams – Byte streams and
Character streams – Reading and Writing Console
– Reading and Writing Files
EXCEPTIONS
 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.
ADVANTAGE OF EXCEPTION
HANDLING
 The core advantage of exception handling is to
maintain the normal flow of the application.
 An exception normally disrupts the normal flow
of the application that is why we use exception
handling.
 Let's take a scenario:
 statement 1;
 statement 2;
 statement 3;
 statement 4;
 statement 5;//exception occurs
ADVANTAGE OF EXCEPTION
HANDLING
 statement 6;
 statement 7;
 statement 8;
 statement 9;
 statement 10;
 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.
DIFFERENCE B/W ERROR AND
EXCEPTION
Sl.
No.
Key Error Exception
1 Type Classified as an
unchecked type
Classified as checked and
unchecked
2 Package It belongs to
java.lang.error
It belongs to
java.lang.Exception
3 Recoverable/
Irrecoverable
It is irrecoverable It is recoverable
4 Which time
the it will be
identified.
It can't be occur at
compile time
It can occur at run time
compile time both
5 Example OutOfMemoryError ,IOE
rror
NullPointerException ,
SqlException
HIERARCHY OF JAVA EXCEPTION
CLASSES
 The java.lang.Throwable class is the root class of
Java Exception hierarchy which is inherited by
two subclasses: Exception and Error.
 A hierarchy of Java Exception classes are given
below:
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
TYPES OF JAVA EXCEPTIONS
 There are mainly two types of exceptions:
checked and unchecked. Here, an error is
considered as the unchecked exception. According
to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
DIFFERENCE BETWEEN CHECKED
AND UNCHECKED EXCEPTIONS
1) Checked Exception
 The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions
e.g. IOException, SQLException etc.
 Checked exceptions are checked at compile-time.
2) Unchecked Exception
 The classes which inherit RuntimeException are known as
unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.
 Unchecked exceptions are not checked at compile-time, but
they are checked at runtime.
3) Error
 Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.
JAVA EXCEPTION KEYWORDS
Keyword Description
try
The "try" keyword is used to specify a block where we
should place exception code. The try block must be
followed by either catch or finally. It means, we can't use
try block alone.
catch
The "catch" block is used to handle the exception. It must
be preceded by try block which means we can't use catch
block alone. It can be followed by finally block later.
finally
The "finally" block is used to execute the important code
of the program. It is executed whether an exception is
handled or not.
throw The "throw" keyword is used to throw an exception.
throws
The "throws" keyword is used to declare exceptions. It
doesn't throw an exception. It specifies that there may
occur an exception in the method. It is always used with
method signature.
COMMON SCENARIOS OF JAVA
EXCEPTIONS
 There are given some scenarios where unchecked
exceptions may occur. They are as follows:
1) A scenario where ArithmeticException occurs
 If we divide any number by zero, there occurs an
ArithmeticException.
 int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
 If we have a null value in any variable, performing any
operation on the variable throws a NullPointerException.
 String s=null;
 System.out.println(s.length());//NullPointerException
COMMON SCENARIOS OF JAVA
EXCEPTIONS
3) A scenario where NumberFormatException occurs
The wrong formatting of any value may occur
NumberFormatException. Suppose I have a string variable that
has characters, converting this variable into digit will occur
NumberFormatException.
 String s="abc";
 int i=Integer.parseInt(s);//NumberFormatException
4)A scenario where ArrayIndexOutOfBoundsException
occurs
If you are inserting any value in the wrong index, it would
result in ArrayIndexOutOfBoundsException as shown below:
 int a[]=new int[5];
 a[10]=50; //ArrayIndexOutOfBoundsException
EXAMPLE
public class Exp1{
public static void main(String args[]){
try{
int data=100/0;
}catch(ArithmeticException e)
{System.out.println(e);}
System.out.println("Rest of the code.....");
}
}
INTERNAL WORKING OF JAVA TRY-
CATCH BLOCK
INTERNAL WORKING OF JAVA TRY-
CATCH BLOCK
 The JVM firstly checks whether the exception is
handled or not. If exception is not handled, JVM
provides a default exception handler that
performs the following tasks:
 Prints out exception description.
 Prints the stack trace (Hierarchy of methods where
the exception occurred).
 Causes the program to terminate.
 But if exception is handled by the application
programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
JAVA CATCH MULTIPLE
EXCEPTIONS
 A try block can be followed by one or more catch
blocks.
 Each catch block must contain a different
exception handler.
 So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-
catch block.
 Points to remember
 At a time only one exception occurs and at a time only
one catch block is executed.
 All catch blocks must be ordered from most specific to
most general, i.e. catch for ArithmeticException must
come before catch for Exception.
EXAMPLE
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0; }
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs"); catch(Arra
yIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occur
s"); }
catch(Exception e) {
System.out.println("Parent Exception occurs"); } System.ou
t.println("rest of the code"); }
}
JAVA NESTED TRY BLOCK
 The try block within a try block is known as
nested try block in java.
 Why use nested try block
 Sometimes a situation may arise where a part of a
block may cause one error and the entire block itself
may cause another error.
 In such cases, exception handlers have to be nested.
SYNTAX
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{ }
}
catch(Exception e)
{
}
....
EXAMPLE
class Excep2{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0; }
catch(ArithmeticExceptione){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsExceptione)
{System.out.println(e);}
System.out.println("other statement");
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow.."); } }
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 follows try or catch block.
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
EXAMPLE
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data); }
catch(NullPointerException e
){System.out.println(e);}
finally
{System.out.println("finally block is always executed");}
}
}
THROWING AND CATCHING
EXCEPTIONS
 The throw keyword in Java is used to explicitly
throw an exception from a method or any block of
code.
 We can throw either
checked or unchecked exception.
 The throw keyword is mainly used to throw
custom exceptions.
Syntax: throw Instance
Example:
throw new ArithmeticException("/ by zero");
EXAMPLE : THROW
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
} }
JAVA THROWS KEYWORD
 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.
 Exception Handling is mainly used to handle the
checked exceptions.

JAVA THROWS KEYWORD
 If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he
is not performing check up before the code being used.
 Syntax of java throws
 return_type method_name() throws exception_class_
name{ //method code }
 Advantage of Java throws keyword
 Now Checked Exception can be propagated
(forwarded in call stack).
 It provides information to the caller of the method
about the exception.

EXAMPLE FOR THROWS
class Test {
static void check() throws ArithmeticException
{ System.out.println("Inside check function");
throw new ArithmeticException("demo"); }
public static void main(String args[]) {
try {
check(); }
catch(ArithmeticException e)
{ System.out.println("caught" + e); } } }
DIFFERENCE BETWEEN THROW &
THROWS
throw throws
throw keyword is used to
throw an exception explicitly.
throws keyword is used to
declare an exception possible
during its execution.
throw keyword is followed by
an instance of Throwable
class or one of its sub-classes.
throws keyword is followed by
one or more Exception class
names separated by commas.
throw keyword is declared
inside a method body.
throws keyword is used with
method signature (method
declaration).
We cannot throw multiple
exceptions using throw
keyword.
We can declare multiple
exceptions (separated by
commas) using throws
keyword.
BUILT-IN EXCEPTIONS
 Java defines several types of exceptions that
relate to its various class libraries.
 Java also allows users to define their own
exceptions.
BUILT-IN EXCEPTIONS
 Built-in exceptions are the exceptions which are
available in Java libraries.
 These exceptions are suitable to explain certain
error situations.
 Below is the list of important built-in exceptions in
Java.
 ArithmeticException
 ArrayIndexOutOfBoundsException
 ClassNotFoundException
 FileNotFoundException
 IOException
BUILT-IN EXCEPTIONS
 InterruptedException
 NoSuchFieldException
 NoSuchMethodException
 NullPointerException
 NumberFormatException
 RuntimeException
 StringIndexOutOfBoundsException
EXAMPLE FOR BUILT IN
EXCEPTION
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException.."
); }
} }
USER DEFINED EXCEPTION
 java we can create our own exception class and
throw that exception using throw keyword.
 These exceptions are known as user-
defined or custom exceptions.
 In this tutorial we will see how to create your
own custom exception and throw it on a
particular condition.
 To understand this tutorial you should have the
basic knowledge of try-catch block and
throw in java.
EXAMPLE
class MyException extends Exception{
String str1;
MyException(String str2) {
str1=str2;}
public String toString(){
return ("MyException Occurred: "+str1) ; }}
public class Example1 {
public static void main(String[] args) {
try{
System.out.println("Starting of try block");
throw new MyException("This is My error Message");}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
} }
STREAMS
 the Stream API is used to process collections of
objects
 is a sequence of data , supports various methods
 Types
 Input Stream : used to read data from a source.
 Output Stream : used for writing data to a destination.
TYPES OF INPUT & OUTPUT
STREAM
I/O STREAMS CLASSES
CONSOLE STREAMS
 In Java, 3 streams are created for us
automatically. All these streams are attached
with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Example:
 System.out.println("simple message");
 System.err.println("error message");
 System.in.read()
BYTE STREAM CLASSES
Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java
standard datatype
DataOutputStream An output stream that contain method for
writing java standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream
output.
PrintStream Output Stream that
contain print() and println() method
CHARACTER STREAM CLASSES
Stream class Description
BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReade
r
Output stream that translate character to byte.
PrintWriter Output Stream that
contain print() and println() method.
Reader Abstract class that define character stream
input
Writer Abstract class that define character stream
output
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
FILE I/O
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:t1.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
import java.io.FileWriter;
public class f12
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("D:t1.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}
catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming

More Related Content

PPTX
Exception handling in java
PPTX
Exception handling in java
PPTX
Lec-01 Exception Handling in Java_javatpoint.pptx
PPTX
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
PPTX
Exception handling in java.pptx
PPTX
using Java Exception Handling in Java.pptx
PPTX
UNIT 2.pptx
PPTX
java exception.pptx
Exception handling in java
Exception handling in java
Lec-01 Exception Handling in Java_javatpoint.pptx
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
Exception handling in java.pptx
using Java Exception Handling in Java.pptx
UNIT 2.pptx
java exception.pptx

Similar to oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming (20)

PPTX
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
PPTX
Interface andexceptions
PPTX
Java exception handling
PPTX
EXCEPTION HANDLING in prograaming
PDF
Ch-1_5.pdf this is java tutorials for all
PPTX
L14 exception handling
PPTX
Unit-4 Java ppt for BCA Students Madras Univ
PPTX
Exception Handling.pptx
PPTX
Chap2 exception handling
PPTX
Java-Unit 3- Chap2 exception handling
PPSX
Java Exceptions
PPSX
Java Exceptions Handling
PDF
Java unit 11
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
PPTX
Exceptionhandling
PPTX
Exception handling
PPTX
Java-Exception Handling Presentation. 2024
PPTX
Exception Handling In Java Presentation. 2024
PPTX
Exception handling and throw and throws keyword in java.pptx
PPTX
Exception‐Handling in object oriented programming
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Interface andexceptions
Java exception handling
EXCEPTION HANDLING in prograaming
Ch-1_5.pdf this is java tutorials for all
L14 exception handling
Unit-4 Java ppt for BCA Students Madras Univ
Exception Handling.pptx
Chap2 exception handling
Java-Unit 3- Chap2 exception handling
Java Exceptions
Java Exceptions Handling
Java unit 11
Java Exception Handling & IO-Unit-3 (1).ppt
Exceptionhandling
Exception handling
Java-Exception Handling Presentation. 2024
Exception Handling In Java Presentation. 2024
Exception handling and throw and throws keyword in java.pptx
Exception‐Handling in object oriented programming
Ad

Recently uploaded (20)

PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Transform Your Business with a Software ERP System
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
System and Network Administraation Chapter 3
PPTX
ai tools demonstartion for schools and inter college
PDF
Understanding Forklifts - TECH EHS Solution
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
System and Network Administration Chapter 2
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Essential Infomation Tech presentation.pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
2025 Textile ERP Trends: SAP, Odoo & Oracle
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Which alternative to Crystal Reports is best for small or large businesses.pdf
wealthsignaloriginal-com-DS-text-... (1).pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Softaken Excel to vCard Converter Software.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Transform Your Business with a Software ERP System
Upgrade and Innovation Strategies for SAP ERP Customers
System and Network Administraation Chapter 3
ai tools demonstartion for schools and inter college
Understanding Forklifts - TECH EHS Solution
How Creative Agencies Leverage Project Management Software.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
System and Network Administration Chapter 2
Wondershare Filmora 15 Crack With Activation Key [2025
Essential Infomation Tech presentation.pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
How to Migrate SBCGlobal Email to Yahoo Easily
Ad

oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming

  • 2. UNIT-III EXCEPTION HANDLING AND I/O Exceptions - Exception hierarchy - throwing and catching exceptions – built-in exceptions, creating own exceptions, Stack Trace Elements. Input / Output Basics – Streams – Byte streams and Character streams – Reading and Writing Console – Reading and Writing Files
  • 3. EXCEPTIONS  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.
  • 4. ADVANTAGE OF EXCEPTION HANDLING  The core advantage of exception handling is to maintain the normal flow of the application.  An exception normally disrupts the normal flow of the application that is why we use exception handling.  Let's take a scenario:  statement 1;  statement 2;  statement 3;  statement 4;  statement 5;//exception occurs
  • 5. ADVANTAGE OF EXCEPTION HANDLING  statement 6;  statement 7;  statement 8;  statement 9;  statement 10;  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.
  • 6. DIFFERENCE B/W ERROR AND EXCEPTION Sl. No. Key Error Exception 1 Type Classified as an unchecked type Classified as checked and unchecked 2 Package It belongs to java.lang.error It belongs to java.lang.Exception 3 Recoverable/ Irrecoverable It is irrecoverable It is recoverable 4 Which time the it will be identified. It can't be occur at compile time It can occur at run time compile time both 5 Example OutOfMemoryError ,IOE rror NullPointerException , SqlException
  • 7. HIERARCHY OF JAVA EXCEPTION CLASSES  The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error.  A hierarchy of Java Exception classes are given below:
  • 9. TYPES OF JAVA EXCEPTIONS  There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According to Oracle, there are three types of exceptions: 1. Checked Exception 2. Unchecked Exception 3. Error
  • 11. DIFFERENCE BETWEEN CHECKED AND UNCHECKED EXCEPTIONS 1) Checked Exception  The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc.  Checked exceptions are checked at compile-time. 2) Unchecked Exception  The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.  Unchecked exceptions are not checked at compile-time, but they are checked at runtime. 3) Error  Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
  • 12. JAVA EXCEPTION KEYWORDS Keyword Description try The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone. catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. finally The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not. throw The "throw" keyword is used to throw an exception. throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.
  • 13. COMMON SCENARIOS OF JAVA EXCEPTIONS  There are given some scenarios where unchecked exceptions may occur. They are as follows: 1) A scenario where ArithmeticException occurs  If we divide any number by zero, there occurs an ArithmeticException.  int a=50/0;//ArithmeticException 2) A scenario where NullPointerException occurs  If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.  String s=null;  System.out.println(s.length());//NullPointerException
  • 14. COMMON SCENARIOS OF JAVA EXCEPTIONS 3) A scenario where NumberFormatException occurs The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that has characters, converting this variable into digit will occur NumberFormatException.  String s="abc";  int i=Integer.parseInt(s);//NumberFormatException 4)A scenario where ArrayIndexOutOfBoundsException occurs If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as shown below:  int a[]=new int[5];  a[10]=50; //ArrayIndexOutOfBoundsException
  • 15. EXAMPLE public class Exp1{ public static void main(String args[]){ try{ int data=100/0; }catch(ArithmeticException e) {System.out.println(e);} System.out.println("Rest of the code....."); } }
  • 16. INTERNAL WORKING OF JAVA TRY- CATCH BLOCK
  • 17. INTERNAL WORKING OF JAVA TRY- CATCH BLOCK  The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:  Prints out exception description.  Prints the stack trace (Hierarchy of methods where the exception occurred).  Causes the program to terminate.  But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.
  • 18. JAVA CATCH MULTIPLE EXCEPTIONS  A try block can be followed by one or more catch blocks.  Each catch block must contain a different exception handler.  So, if you have to perform different tasks at the occurrence of different exceptions, use java multi- catch block.  Points to remember  At a time only one exception occurs and at a time only one catch block is executed.  All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
  • 19. EXAMPLE public class MultipleCatchBlock1 { public static void main(String[] args) { try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e) { System.out.println("Arithmetic Exception occurs"); catch(Arra yIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occur s"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.ou t.println("rest of the code"); } }
  • 20. JAVA NESTED TRY BLOCK  The try block within a try block is known as nested try block in java.  Why use nested try block  Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error.  In such cases, exception handlers have to be nested.
  • 21. SYNTAX try { statement 1; statement 2; try { statement 1; statement 2; } catch(Exception e) { } } catch(Exception e) { } ....
  • 22. EXAMPLE class Excep2{ public static void main(String args[]){ try{ try{ System.out.println("going to divide"); int b =39/0; } catch(ArithmeticExceptione){System.out.println(e);} try{ int a[]=new int[5]; a[5]=4; }catch(ArrayIndexOutOfBoundsExceptione) {System.out.println(e);} System.out.println("other statement"); }catch(Exception e){System.out.println("handeled");} System.out.println("normal flow.."); } }
  • 23. 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 follows try or catch block.
  • 25. EXAMPLE class TestFinallyBlock{ public static void main(String args[]){ try{ int data=25/5; System.out.println(data); } catch(NullPointerException e ){System.out.println(e);} finally {System.out.println("finally block is always executed");} } }
  • 26. THROWING AND CATCHING EXCEPTIONS  The throw keyword in Java is used to explicitly throw an exception from a method or any block of code.  We can throw either checked or unchecked exception.  The throw keyword is mainly used to throw custom exceptions. Syntax: throw Instance Example: throw new ArithmeticException("/ by zero");
  • 27. EXAMPLE : THROW public class TestThrow1{ static void validate(int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ validate(13); System.out.println("rest of the code..."); } }
  • 28. JAVA THROWS KEYWORD  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.  Exception Handling is mainly used to handle the checked exceptions. 
  • 29. JAVA THROWS KEYWORD  If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.  Syntax of java throws  return_type method_name() throws exception_class_ name{ //method code }  Advantage of Java throws keyword  Now Checked Exception can be propagated (forwarded in call stack).  It provides information to the caller of the method about the exception. 
  • 30. EXAMPLE FOR THROWS class Test { static void check() throws ArithmeticException { System.out.println("Inside check function"); throw new ArithmeticException("demo"); } public static void main(String args[]) { try { check(); } catch(ArithmeticException e) { System.out.println("caught" + e); } } }
  • 31. DIFFERENCE BETWEEN THROW & THROWS throw throws throw keyword is used to throw an exception explicitly. throws keyword is used to declare an exception possible during its execution. throw keyword is followed by an instance of Throwable class or one of its sub-classes. throws keyword is followed by one or more Exception class names separated by commas. throw keyword is declared inside a method body. throws keyword is used with method signature (method declaration). We cannot throw multiple exceptions using throw keyword. We can declare multiple exceptions (separated by commas) using throws keyword.
  • 32. BUILT-IN EXCEPTIONS  Java defines several types of exceptions that relate to its various class libraries.  Java also allows users to define their own exceptions.
  • 33. BUILT-IN EXCEPTIONS  Built-in exceptions are the exceptions which are available in Java libraries.  These exceptions are suitable to explain certain error situations.  Below is the list of important built-in exceptions in Java.  ArithmeticException  ArrayIndexOutOfBoundsException  ClassNotFoundException  FileNotFoundException  IOException
  • 34. BUILT-IN EXCEPTIONS  InterruptedException  NoSuchFieldException  NoSuchMethodException  NullPointerException  NumberFormatException  RuntimeException  StringIndexOutOfBoundsException
  • 35. EXAMPLE FOR BUILT IN EXCEPTION class NullPointer_Demo { public static void main(String args[]) { try { String a = null; //null value System.out.println(a.charAt(0)); } catch(NullPointerException e) { System.out.println("NullPointerException.." ); } } }
  • 36. USER DEFINED EXCEPTION  java we can create our own exception class and throw that exception using throw keyword.  These exceptions are known as user- defined or custom exceptions.  In this tutorial we will see how to create your own custom exception and throw it on a particular condition.  To understand this tutorial you should have the basic knowledge of try-catch block and throw in java.
  • 37. EXAMPLE class MyException extends Exception{ String str1; MyException(String str2) { str1=str2;} public String toString(){ return ("MyException Occurred: "+str1) ; }} public class Example1 { public static void main(String[] args) { try{ System.out.println("Starting of try block"); throw new MyException("This is My error Message");} catch(MyException exp){ System.out.println("Catch Block") ; System.out.println(exp) ; } } }
  • 38. STREAMS  the Stream API is used to process collections of objects  is a sequence of data , supports various methods  Types  Input Stream : used to read data from a source.  Output Stream : used for writing data to a destination.
  • 39. TYPES OF INPUT & OUTPUT STREAM
  • 41. CONSOLE STREAMS  In Java, 3 streams are created for us automatically. All these streams are attached with the console. 1) System.out: standard output stream 2) System.in: standard input stream 3) System.err: standard error stream Example:  System.out.println("simple message");  System.err.println("error message");  System.in.read()
  • 42. BYTE STREAM CLASSES Stream class Description BufferedInputStream Used for Buffered Input Stream. BufferedOutputStream Used for Buffered Output Stream. DataInputStream Contains method for reading java standard datatype DataOutputStream An output stream that contain method for writing java standard data type FileInputStream Input stream that reads from a file FileOutputStream Output stream that write to a file. InputStream Abstract class that describe stream input. OutputStream Abstract class that describe stream output. PrintStream Output Stream that contain print() and println() method
  • 43. CHARACTER STREAM CLASSES Stream class Description BufferedReader Handles buffered input stream. BufferedWriter Handles buffered output stream. FileReader Input stream that reads from file. FileWriter Output stream that writes to file. InputStreamReader Input stream that translate byte to character OutputStreamReade r Output stream that translate character to byte. PrintWriter Output Stream that contain print() and println() method. Reader Abstract class that define character stream input Writer Abstract class that define character stream output
  • 47. FILE I/O import java.io.FileReader; public class FileReaderExample { public static void main(String args[])throws Exception{ FileReader fr=new FileReader("D:t1.txt"); int i; while((i=fr.read())!=-1) System.out.print((char)i); fr.close(); } }
  • 49. import java.io.FileWriter; public class f12 { public static void main(String args[]) { try { FileWriter fw=new FileWriter("D:t1.txt"); fw.write("Welcome to javaTpoint."); fw.close(); } catch(Exception e){System.out.println(e);} System.out.println("Success..."); } }