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
Ad

More Related Content

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

java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
SukhpreetSingh519414
 
1.12 Exception Handing.pptx
1.12 Exception Handing.pptx1.12 Exception Handing.pptx
1.12 Exception Handing.pptx
YashiUPADHYAY6
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Java chapter 6
Java chapter 6Java chapter 6
Java chapter 6
Abdii Rashid
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception handling and throw and throws keyword in java.pptx
Exception handling and throw and throws keyword in java.pptxException handling and throw and throws keyword in java.pptx
Exception handling and throw and throws keyword in java.pptx
shikhaverma566116
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Lec-01 Exception Handling in Java_javatpoint.pptx
Lec-01 Exception Handling in Java_javatpoint.pptxLec-01 Exception Handling in Java_javatpoint.pptx
Lec-01 Exception Handling in Java_javatpoint.pptx
MdNazmulHasanRuhan1
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
Shipra Swati
 
1.12 Exception Handing.pptx
1.12 Exception Handing.pptx1.12 Exception Handing.pptx
1.12 Exception Handing.pptx
YashiUPADHYAY6
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception handling and throw and throws keyword in java.pptx
Exception handling and throw and throws keyword in java.pptxException handling and throw and throws keyword in java.pptx
Exception handling and throw and throws keyword in java.pptx
shikhaverma566116
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Lec-01 Exception Handling in Java_javatpoint.pptx
Lec-01 Exception Handling in Java_javatpoint.pptxLec-01 Exception Handling in Java_javatpoint.pptx
Lec-01 Exception Handling in Java_javatpoint.pptx
MdNazmulHasanRuhan1
 

Recently uploaded (20)

How I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetryHow I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetry
Cees Bos
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
sequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineeringsequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineering
aashrithakondapalli8
 
Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??
Web Designer
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Unit Two - Java Architecture and OOPS
Unit Two  -   Java Architecture and OOPSUnit Two  -   Java Architecture and OOPS
Unit Two - Java Architecture and OOPS
Nabin Dhakal
 
NYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdfNYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdf
AUGNYC
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
Download 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-ActivatedDownload 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-Activated
Web Designer
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
How I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetryHow I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetry
Cees Bos
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
sequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineeringsequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineering
aashrithakondapalli8
 
Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??
Web Designer
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Unit Two - Java Architecture and OOPS
Unit Two  -   Java Architecture and OOPSUnit Two  -   Java Architecture and OOPS
Unit Two - Java Architecture and OOPS
Nabin Dhakal
 
NYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdfNYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdf
AUGNYC
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
Download 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-ActivatedDownload 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-Activated
Web Designer
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
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..."); } }
  翻译: