SlideShare a Scribd company logo
Exception Handling
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
2
Why?
 Users may use our programs in an unexpected ways.
 Due to design errors or coding errors, programs may fail in
unexpected ways during execution, or may result in an
abnormal/abrupt program termination
 It is programmer’s responsibility to produce robust code
that does not fail unexpectedly.
 Consequently, programmer must design error handling
into our programs.
 Java – provides clear mechanism to Handle the Exceptions
that happen during program execution.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
3
What you know…
 In C, using the term “ERROR” is used to represent the
unexpected interruption of code execution.
 Two types:
 Compile time Errors (Syntax and Semantic error)
 Runtime Errors (errors)
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
4
Common Runtime Errors
 Dividing a number by zero.
 Accessing an element that is out of bounds of an
array.
 Trying to store incompatible data elements.
 Using negative value as array size.
 Trying to convert from string data to a specific data
value (e.g., converting string “abc” to integer value).
 File errors:
 Opening the file that does not exist
 opening a file in “read mode” that does not exist or
no read permission
 Opening a file in “write/update mode” which has
“read only” permission.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
5
Exceptions Handling in Java
 An abnormal condition that arises in a code sequence at
run time.
 In other words, an exception is a run-time error.
 A Java exception is an object that describes an
exceptional (that is, error) condition that has occurred in
a piece of code.
 When an exceptional condition arises, an object
representing that exception is created and thrown in the
method that caused the error.
 A program can deal with an exception object in one of
three ways:
 ignore it
 handle it where it occurs
 handle it an another place in the programDr. P. Victer Paul, Indian Institute of Information Technology Kottayam
6
Exceptions Handling in Java
 Java provides a robust and object oriented way to handle
exception scenarios, known as Java Exception Handling.
 Java exception handling is managed via five keywords: try,
catch, throw, throws, and finally.
 Program statements that you want to monitor for
exceptions are contained within a try block.
 Catch block can handle it in some rational manner.
 System-generated exceptions are automatically thrown by the Java
run-time system.
 To manually throw an exception, use the keyword throw.
 Any exception that is thrown out of a method must be
specified as such by a throws clause.
 Any code that must be executed after a try block
completes (with/without exception)is put in a finally block.Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
7
Syntax of Exception Handling Code
…
…
try {
// statements
}
catch( Exception-Type e)
{
// statements to process exception
}
..
..
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
8
Without Exception Handling
class WithoutExceptionHandling{
public static void main(String[] args){
int a,b; float r;
a = 7; b = 0;
r = a/b;
System.out.println(“Result is “ + r);
System.out.println(“Program reached this line”);
}
} Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
9
With Exception Handling
class WithExceptionHandling{
public static void main(String[] args){
int a,b; float r;
a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
}
System.out.println(“Program reached this line”);
}
}
Program
Reaches here
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
10
Exception Hierarchy
 All exception types are subclasses of the built-in class
Throwable.
 Throwable is at the top of the exception class hierarchy.
 Throwable are two subclasses partition exceptions into
two distinct branches.
 Exceptions
 Errors
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
11
Java Exception Class Hierarchy
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
12
Exception Class
 Exception is used for exceptional conditions that user
programs should catch.
 This class is inherited to create subclass as programmer’s
own custom exception types.
 There is an important subclass of Exception, called
RuntimeException.
 Exceptions of this type are automatically defined for the
programs that a programmer write.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
13
Exception Class
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Exception describes errors
caused by your program
and external
circumstances. These
errors can be caught and
handled by your program.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
14
Runtime Exceptions
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
RuntimeException is caused by
programming errors, such as bad
casting, accessing an out-of-bounds
array, and numeric errors.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
15
Error Exception
 The Error defines exceptions that are not expected to be
caught under normal circumstances by your program.
 Exceptions of type Error are used by the Java run-time
system to indicate errors having to do with the run-time
environment, itself.
 Stack overflow is an example of such an error.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
16
Error Exception Types
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
System errors are thrown by JVM
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
occur. If one does, there is little
you can do beyond notifying the
user and trying to terminate the
program gracefully.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
17
Error Exception Types
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
18
Poll Question
 Consider the JVM stops execution of a java program due
to shortage of JVM memory. This scenario is
 A. Runtime Exception
 B. Error
 C. Checked Exception
 D. Exception
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
19
Exception Types
 Exceptions fall into two categories:
 Checked Exceptions
 Unchecked Exceptions
 Checked exceptions are inherited from the core Java class
Exception.
 represent compile time exceptions that are coder responsibility to
check.
 the compiler will issue an error message.
 RuntimeException, Error and their subclasses are known
as unchecked exceptions.
 if not handled, your program will terminate with an appropriate
error message.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
20
Exception Types
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
21
Exception Types
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Unchecked
exception.
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
22
what happens when don’t handle
The call stack is quite useful for debugging, because it pinpoints the
precise sequence of steps that led to the errorDr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Predict the output
23Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
24
Poll Question
Output??
 A Compile Error
 B Inside
 C Inside
rest of the code
 D Inside
Null
rest of the code
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Handling Exception
 Different mechanism.
 Simple try - catch
 try with multiple catch
 multiple exception with single catch
 nested try statements
 throw
 Throws
 try, catch and finally (exception with exit code)
 Java Exception Propagation
25Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Simple try - catch
 The try block allows you to define a block of code to be
tested/monitor for errors while it is being executed.
 The catch block allows you to define a block of code to be
executed, if an error occurs in the try block.
26Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Example
27Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Try with multiple catch
 In some cases, more than one exception
could be raised by a single piece of
code.
 To handle this type of situation, you can
specify two or more catch clauses, each
catching a different type of exception.
 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
28Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Try with multiple catch Ex
29Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
multiple exception with single catch
 When you use multiple catch statements, it is important
to remember that exception subclasses must come
before any of their superclasses.
 This is because a catch statement that uses a superclass
will catch exceptions of that type plus any of its
subclasses. Thus, a subclass would never be reached if it
came after its superclass.
 Further, in Java, unreachable code is an error.
30Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
multiple exception with single catch Ex
31Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
multiple exception with single catch Ex
32Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
nested try statements
 The try statement can be nested.
 That is, a try statement can be inside the block of another
try.
 If an inner try statement does not have a catch handler
for a particular exception, the stack is unwound and the
next try statement’s catch handlers are inspected for a
match.
 This continues until one of the catch statements succeeds,
or until all of the nested try statements are exhausted.
 If no catch statement matches, then the Java run-time
system will handle the exception
33Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
nested try statements Ex
34Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
35
Poll Question
 Which of these is a super class of all errors and exceptions
in the Java language?
 A RunTimeExceptions
 B Throwable
 C Catchable
 D None of the above
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Handling Exception
 Different mechanism.
 Simple try - catch
 try with multiple catch
 multiple exception with single catch
 nested try statements
 throw
 Throws
 try, catch and finally (exception with exit code)
 Java Exception Propagation
36Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
throw
 So far, you have only been catching exceptions that are
thrown by the Java run-time system.
 However, it is possible for your program to throw an
exception explicitly, using the throw statement.
 Syntax:
 Here, ThrowableInstance must be an object of type
Throwable or a subclass of Throwable.
 The flow of execution stops immediately after the throw
statement; any subsequent statements are not executed.
 If no matching catch is found, then the default exception
handler halts the program and prints the stack trace
37Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
throw
38Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
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.
 You do this by including a throws clause in the method’s
declaration.
 A throws clause lists the types of exceptions that a
method might throw.
 This is necessary for all exceptions, except those of type
Error or RuntimeException, or any of their subclasses.
 If they are not, a compile-time error will result.
39Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Throws
 This is the general form of a method declaration that
includes a throws clause:
 exception-list is a comma-separated list of the exceptions
that a method can throw.
 First, you need to declare that throwOne( ) throws
IllegalAccessException.
 Second, main( ) must define a try/catch statement that
catches this exception.
40Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Throws
41Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Throws
42Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
try, catch and finally
 When exceptions are thrown, execution in a method takes
a rather abrupt, nonlinear path that alters the normal
flow through the method.
 This could be a problem in some methods. For example,
 if a method opens a file upon entry and closes it upon
exit,
 then you will not want the code that closes the file to
be bypassed by the exception-handling mechanism.
 The finally keyword is designed to address this
contingency
43Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
try, catch and finally
 finally creates a block of code that will be executed after
a try/catch block has completed and
 before the code following the try/catch block.
 The finally block will execute whether or not an exception
is thrown.
44Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
try, catch and finally
45Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Java’s Built-in Exceptions
 Inside the standard package java.lang, Java defines
several exception classes.
 A few have been used by the preceding examples.
46Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Java’s Built-in Exceptions
47Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Java’s Built-in Exceptions
48Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Creating Your Exception Subclasses
 Although Java’s built-in exceptions handle most common
errors
 user probably want to create your own exception types to
handle situations specific to your applications.
 This is quite easy to do: just define a subclass of
Exception (which is, of course, a subclass of Throwable).
class UserException extends Exception
{
}
49Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Creating Your Exception Subclasses
class InvalidMobile extends Exception
{
InvalidMobile(String msg)
{
super(msg);
}
}
50Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Creating Your Exception Subclasses
51Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Creating Your Exception Subclasses
52Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
53
The End…
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Ad

More Related Content

What's hot (20)

Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
Madishetty Prathibha
 
Inter Thread Communicationn.pptx
Inter Thread Communicationn.pptxInter Thread Communicationn.pptx
Inter Thread Communicationn.pptx
SelvakumarNSNS
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
Madishetty Prathibha
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
History Of JAVA
History Of JAVAHistory Of JAVA
History Of JAVA
ARSLANAHMED107
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Pavith Gunasekara
 
Exception handling
Exception handlingException handling
Exception handling
PhD Research Scholar
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
PhD Research Scholar
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Ankit Rai
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
Ravi Chythanya
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVA
Mehak Tawakley
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
JayasankarPR2
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
Haris Bin Zahid
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Lovely Professional University
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
Elizabeth alexander
 

Similar to Java - Exception Handling Concepts (20)

Itp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & AssertionsItp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & Assertions
phanleson
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
JAVA Presenttation topics Programs.pptx
JAVA  Presenttation topics Programs.pptxJAVA  Presenttation topics Programs.pptx
JAVA Presenttation topics Programs.pptx
RitikSharma685066
 
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
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Exception handling
Exception handlingException handling
Exception handling
Karthik Sekar
 
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.pptComputer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
ShafiEsa1
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
FacultyAnupamaAlagan
 
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 in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.net
suraj pandey
 
Itp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & AssertionsItp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & Assertions
phanleson
 
JAVA Presenttation topics Programs.pptx
JAVA  Presenttation topics Programs.pptxJAVA  Presenttation topics Programs.pptx
JAVA Presenttation topics Programs.pptx
RitikSharma685066
 
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
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.pptComputer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
ShafiEsa1
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
FacultyAnupamaAlagan
 
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 in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.net
suraj pandey
 
Ad

More from Victer Paul (13)

OOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Sequence and Communication Diagrams - LabOOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Sequence and Communication Diagrams - Lab
Victer Paul
 
OOAD - UML - Class and Object Diagrams - Lab
OOAD - UML - Class and Object Diagrams - LabOOAD - UML - Class and Object Diagrams - Lab
OOAD - UML - Class and Object Diagrams - Lab
Victer Paul
 
OOAD - Systems and Object Orientation Concepts
OOAD - Systems and Object Orientation ConceptsOOAD - Systems and Object Orientation Concepts
OOAD - Systems and Object Orientation Concepts
Victer Paul
 
Java - Strings Concepts
Java - Strings ConceptsJava - Strings Concepts
Java - Strings Concepts
Victer Paul
 
Java - Packages Concepts
Java - Packages ConceptsJava - Packages Concepts
Java - Packages Concepts
Victer Paul
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java Basics
Victer Paul
 
Java - Class Structure
Java - Class StructureJava - Class Structure
Java - Class Structure
Victer Paul
 
Java - Object Oriented Programming Concepts
Java - Object Oriented Programming ConceptsJava - Object Oriented Programming Concepts
Java - Object Oriented Programming Concepts
Victer Paul
 
Java - Basic Concepts
Java - Basic ConceptsJava - Basic Concepts
Java - Basic Concepts
Victer Paul
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
Java - Inheritance Concepts
Java - Inheritance ConceptsJava - Inheritance Concepts
Java - Inheritance Concepts
Victer Paul
 
Java - Arrays Concepts
Java - Arrays ConceptsJava - Arrays Concepts
Java - Arrays Concepts
Victer Paul
 
Java applet programming concepts
Java  applet programming conceptsJava  applet programming concepts
Java applet programming concepts
Victer Paul
 
OOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Sequence and Communication Diagrams - LabOOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Sequence and Communication Diagrams - Lab
Victer Paul
 
OOAD - UML - Class and Object Diagrams - Lab
OOAD - UML - Class and Object Diagrams - LabOOAD - UML - Class and Object Diagrams - Lab
OOAD - UML - Class and Object Diagrams - Lab
Victer Paul
 
OOAD - Systems and Object Orientation Concepts
OOAD - Systems and Object Orientation ConceptsOOAD - Systems and Object Orientation Concepts
OOAD - Systems and Object Orientation Concepts
Victer Paul
 
Java - Strings Concepts
Java - Strings ConceptsJava - Strings Concepts
Java - Strings Concepts
Victer Paul
 
Java - Packages Concepts
Java - Packages ConceptsJava - Packages Concepts
Java - Packages Concepts
Victer Paul
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java Basics
Victer Paul
 
Java - Class Structure
Java - Class StructureJava - Class Structure
Java - Class Structure
Victer Paul
 
Java - Object Oriented Programming Concepts
Java - Object Oriented Programming ConceptsJava - Object Oriented Programming Concepts
Java - Object Oriented Programming Concepts
Victer Paul
 
Java - Basic Concepts
Java - Basic ConceptsJava - Basic Concepts
Java - Basic Concepts
Victer Paul
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
Java - Inheritance Concepts
Java - Inheritance ConceptsJava - Inheritance Concepts
Java - Inheritance Concepts
Victer Paul
 
Java - Arrays Concepts
Java - Arrays ConceptsJava - Arrays Concepts
Java - Arrays Concepts
Victer Paul
 
Java applet programming concepts
Java  applet programming conceptsJava  applet programming concepts
Java applet programming concepts
Victer Paul
 
Ad

Recently uploaded (20)

Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of ExchangesJignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah Innovator
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Does Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should KnowDoes Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should Know
Pornify CC
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
The Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI IntegrationThe Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI Integration
Re-solution Data Ltd
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
BookNet Canada
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of ExchangesJignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah Innovator
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Does Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should KnowDoes Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should Know
Pornify CC
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
The Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI IntegrationThe Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI Integration
Re-solution Data Ltd
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
BookNet Canada
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 

Java - Exception Handling Concepts

  • 1. Exception Handling Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 2. 2 Why?  Users may use our programs in an unexpected ways.  Due to design errors or coding errors, programs may fail in unexpected ways during execution, or may result in an abnormal/abrupt program termination  It is programmer’s responsibility to produce robust code that does not fail unexpectedly.  Consequently, programmer must design error handling into our programs.  Java – provides clear mechanism to Handle the Exceptions that happen during program execution. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 3. 3 What you know…  In C, using the term “ERROR” is used to represent the unexpected interruption of code execution.  Two types:  Compile time Errors (Syntax and Semantic error)  Runtime Errors (errors) Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 4. 4 Common Runtime Errors  Dividing a number by zero.  Accessing an element that is out of bounds of an array.  Trying to store incompatible data elements.  Using negative value as array size.  Trying to convert from string data to a specific data value (e.g., converting string “abc” to integer value).  File errors:  Opening the file that does not exist  opening a file in “read mode” that does not exist or no read permission  Opening a file in “write/update mode” which has “read only” permission. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 5. 5 Exceptions Handling in Java  An abnormal condition that arises in a code sequence at run time.  In other words, an exception is a run-time error.  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.  When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.  A program can deal with an exception object in one of three ways:  ignore it  handle it where it occurs  handle it an another place in the programDr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 6. 6 Exceptions Handling in Java  Java provides a robust and object oriented way to handle exception scenarios, known as Java Exception Handling.  Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.  Program statements that you want to monitor for exceptions are contained within a try block.  Catch block can handle it in some rational manner.  System-generated exceptions are automatically thrown by the Java run-time system.  To manually throw an exception, use the keyword throw.  Any exception that is thrown out of a method must be specified as such by a throws clause.  Any code that must be executed after a try block completes (with/without exception)is put in a finally block.Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 7. 7 Syntax of Exception Handling Code … … try { // statements } catch( Exception-Type e) { // statements to process exception } .. .. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 8. 8 Without Exception Handling class WithoutExceptionHandling{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; r = a/b; System.out.println(“Result is “ + r); System.out.println(“Program reached this line”); } } Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 9. 9 With Exception Handling class WithExceptionHandling{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(“Result is “ + r); } catch(ArithmeticException e){ System.out.println(“ B is zero); } System.out.println(“Program reached this line”); } } Program Reaches here Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 10. 10 Exception Hierarchy  All exception types are subclasses of the built-in class Throwable.  Throwable is at the top of the exception class hierarchy.  Throwable are two subclasses partition exceptions into two distinct branches.  Exceptions  Errors Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 11. 11 Java Exception Class Hierarchy LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 12. 12 Exception Class  Exception is used for exceptional conditions that user programs should catch.  This class is inherited to create subclass as programmer’s own custom exception types.  There is an important subclass of Exception, called RuntimeException.  Exceptions of this type are automatically defined for the programs that a programmer write. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 13. 13 Exception Class LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 14. 14 Runtime Exceptions LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 15. 15 Error Exception  The Error defines exceptions that are not expected to be caught under normal circumstances by your program.  Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself.  Stack overflow is an example of such an error. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 16. 16 Error Exception Types LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 17. 17 Error Exception Types Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 18. 18 Poll Question  Consider the JVM stops execution of a java program due to shortage of JVM memory. This scenario is  A. Runtime Exception  B. Error  C. Checked Exception  D. Exception Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 19. 19 Exception Types  Exceptions fall into two categories:  Checked Exceptions  Unchecked Exceptions  Checked exceptions are inherited from the core Java class Exception.  represent compile time exceptions that are coder responsibility to check.  the compiler will issue an error message.  RuntimeException, Error and their subclasses are known as unchecked exceptions.  if not handled, your program will terminate with an appropriate error message. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 20. 20 Exception Types Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 21. 21 Exception Types LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException Unchecked exception. Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 22. 22 what happens when don’t handle The call stack is quite useful for debugging, because it pinpoints the precise sequence of steps that led to the errorDr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 23. Predict the output 23Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 24. 24 Poll Question Output??  A Compile Error  B Inside  C Inside rest of the code  D Inside Null rest of the code Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 25. Handling Exception  Different mechanism.  Simple try - catch  try with multiple catch  multiple exception with single catch  nested try statements  throw  Throws  try, catch and finally (exception with exit code)  Java Exception Propagation 25Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 26. Simple try - catch  The try block allows you to define a block of code to be tested/monitor for errors while it is being executed.  The catch block allows you to define a block of code to be executed, if an error occurs in the try block. 26Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 27. Example 27Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 28. Try with multiple catch  In some cases, more than one exception could be raised by a single piece of code.  To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception.  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 28Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 29. Try with multiple catch Ex 29Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 30. multiple exception with single catch  When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their superclasses.  This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its superclass.  Further, in Java, unreachable code is an error. 30Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 31. multiple exception with single catch Ex 31Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 32. multiple exception with single catch Ex 32Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 33. nested try statements  The try statement can be nested.  That is, a try statement can be inside the block of another try.  If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match.  This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted.  If no catch statement matches, then the Java run-time system will handle the exception 33Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 34. nested try statements Ex 34Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 35. 35 Poll Question  Which of these is a super class of all errors and exceptions in the Java language?  A RunTimeExceptions  B Throwable  C Catchable  D None of the above Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 36. Handling Exception  Different mechanism.  Simple try - catch  try with multiple catch  multiple exception with single catch  nested try statements  throw  Throws  try, catch and finally (exception with exit code)  Java Exception Propagation 36Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 37. throw  So far, you have only been catching exceptions that are thrown by the Java run-time system.  However, it is possible for your program to throw an exception explicitly, using the throw statement.  Syntax:  Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.  The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.  If no matching catch is found, then the default exception handler halts the program and prints the stack trace 37Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 38. throw 38Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 39. 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.  You do this by including a throws clause in the method’s declaration.  A throws clause lists the types of exceptions that a method might throw.  This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses.  If they are not, a compile-time error will result. 39Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 40. Throws  This is the general form of a method declaration that includes a throws clause:  exception-list is a comma-separated list of the exceptions that a method can throw.  First, you need to declare that throwOne( ) throws IllegalAccessException.  Second, main( ) must define a try/catch statement that catches this exception. 40Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 41. Throws 41Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 42. Throws 42Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 43. try, catch and finally  When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the normal flow through the method.  This could be a problem in some methods. For example,  if a method opens a file upon entry and closes it upon exit,  then you will not want the code that closes the file to be bypassed by the exception-handling mechanism.  The finally keyword is designed to address this contingency 43Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 44. try, catch and finally  finally creates a block of code that will be executed after a try/catch block has completed and  before the code following the try/catch block.  The finally block will execute whether or not an exception is thrown. 44Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 45. try, catch and finally 45Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 46. Java’s Built-in Exceptions  Inside the standard package java.lang, Java defines several exception classes.  A few have been used by the preceding examples. 46Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 47. Java’s Built-in Exceptions 47Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 48. Java’s Built-in Exceptions 48Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 49. Creating Your Exception Subclasses  Although Java’s built-in exceptions handle most common errors  user probably want to create your own exception types to handle situations specific to your applications.  This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable). class UserException extends Exception { } 49Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 50. Creating Your Exception Subclasses class InvalidMobile extends Exception { InvalidMobile(String msg) { super(msg); } } 50Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 51. Creating Your Exception Subclasses 51Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 52. Creating Your Exception Subclasses 52Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 53. 53 The End… Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  翻译: