SlideShare a Scribd company logo
1 of 45
EXCEPTION
HANDLING
Exception
• An exception is an abnormal condition that
arises in a code sequence at run time.
• 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
• That method maychoose to handle it self
or pass it on.
• At some point the exception is caught and
processed
• Exceptions can be generated by java run
time system or can be manually generated
by your code.
• JRE generates exceptions when you
violate the rules of java language or the
constraints of java execution environment.
• Manually generated exceptions are
typically used to report some error
condition to the caller of a method.
• 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
• If an exception occurs within the try block, it is
thrown
• Your code can catch this exception (using
catch) and handle it
• 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 absolutely must be executed
before a method returns is put in a finally block
• This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}
Exception Types
• All exception types are subclasses of the built-in
class Throwable
• Immediately below Throwable are two
subclasses that partition exceptions into two
distinct branches
• One branch is headed by Exception
• This class is used for exceptional conditions that
user programs should catch
• There is an important subclass of
Exception, called RuntimeException
• Exceptions of this type are automatically
defined for the programs that you write
and include things such as division by
zero and invalid array indexing
• The other branch is topped by Error, which
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
Uncaught Exceptions
• class Exc0 {
• public static void main(String args[]) {
• int d = 0;
• int a = 42 / d;
• }
• }
• Java.lang.ArithmeticException: /by zero at
Exc0.main(Exco.java:4)
• When JRE detects the attempt to /0 it
constrcucts a new exception object and throws
this exception
• This causes the execution of Exc0 to stop
because once an exception is generated it
should be caught some where.In this case we
have not supplied any handler so default handler
of JRE gets called.
• Default handler displays string describing the
exception and the stack trace from the point at
which exception has occurred and terminates
the program.
• class Exc1 {
• static void subroutine() {
• int d = 0;
• int a = 10 / d;
• }
• public static void main(String args[]) {
• Exc1.subroutine();
• }
• }
• Java.lang.ArithmeticException: /by zero
• at Exc1.subroutine(Exc1.java:4)
• at Exc1.main(Exc1.java:7)
Using try and catch
• Handling an exception manually provides
two benefits
• First, it allows you to fix the error
• Second, it prevents the program from
automatically terminating
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero
error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
} o/p:
This program generates the following output:
Division by zero.
• A try and its catch statement form a unit
• The scope of the catch clause is restricted
to those statements specified by the
immediately preceding try statement
• A catch statement cannot catch an
exception thrown by another try statement
// Handle an exception and move on.
import java.util.Random;
class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
} catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
Displaying a Description of an
Exception
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
Exception: java.lang.ArithmeticException: /
by zero
Multiple catch Clauses
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
• Java MultiCatch
• a=0
• Divide by 0:java.lang.ArithmeticException:/by zero
• After try/catch blocks
OR
• Java MultiCatch TestArg
• a=1
• Array index
oob:java.lang.ArrayIndexOutOfBoundsException:42
• After try/catch blocks
/* This program contains an error. A subclass must come
before its superclass in a series of catch statements. If
not, unreachable code will be created and a compile-
time error will result. */
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
} catch(Exception e) {
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because ArithmeticException
is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR - unreachable
System.out.println("This is never reached.");
}
}
Nested try Statements
• Each time a try statement is entered, the
context of that exception is pushed on the
stack
• // An example nested try statements.
• class NestTry {
• public static void main(String args[]) {
• try {
• int a = args.length;
• /* If no command line args are present,
• the following statement will generate
• a divide-by-zero exception. */
• int b = 42 / a;
• System.out.println("a = " + a);
• try { // nested try block
• /* If one command line arg is used,
• then an divide-by-zero exception
• will be generated by the following code. */
• if(a==1) a = a/(a-a); // division by zero
• /* If two command line args are used
• then generate an out-of-bounds exception. */
• if(a==2) {
• int c[] = { 1 };
• c[42] = 99; // generate an out-of-bounds exception
• }
• } catch(ArrayIndexOutOfBoundsException e) {
• System.out.println("Array index out-of-bounds: " + e);
• }
• } catch(ArithmeticException e) {
• System.out.println("Divide by 0: " + e);
• }
• }
• }
• /* Try statements can be implicitly nested via
• calls to methods. */
• class MethNestTry {
• static void nesttry(int a) {
• try { // nested try block
• /* If one command line arg is used,
• then an divide-by-zero exception
• will be generated by the following code. */
• if(a==1) a = a/(a-a); // division by zero
• /* If two command line args are used
• then generate an out-of-bounds exception. */
• if(a==2) {
• int c[] = { 1 };
• c[42] = 99; // generate an out-of-bounds exception
• }
• } catch(ArrayIndexOutOfBoundsException e) {
• System.out.println("Array index out-of-bounds: " + e);
• }
• }
• public static void main(String args[]) {
• try {
• int a = args.length;
• /* If no command line args are present,
• the following statement will generate
• a divide-by-zero exception. */
• int b = 42 / a;
• System.out.println("a = " + a);
• nesttry(a);
• } catch(ArithmeticException e) {
• System.out.println("Divide by 0: " + e);
• }
• }
• }
throw
• It is possible for your program to throw an
exception explicitly, using the throw
statement
• The general form of throw is shown here:
throw ThrowableInstance;
• Here, ThrowableInstance must be an
object of type Throwable or a subclass of
Throwable
• There are two ways you can obtain a
Throwable object: using a parameter into
a catch clause, or creating one with the
new operator
• The flow of execution stops immediately
after the throw statement; any
subsequent statements are not executed
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
} } }
Output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
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
• A throws clause lists the types of exceptions
that a method might throw
• Exceptions that a method can throw must be
declared in the throws clause
• This is the general form of a method declaration
that includes a throws clause:
type method-name(parameter-list) throws
exception-list
{
// body of method
}
• Here, exception-list is a comma-separated list of
the exceptions that a method can throw
// This program contains an error and will
not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[ ]) {
throwOne();
}
}
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example
program:
inside throwOne
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
• If an exception is thrown, the finally block will
execute even if no catch statement matches the
exception
• The finally clause is optional
• Each try statement requires at least one
catch or a finally clause
// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
Here is the output generated by the
preceding program:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally
Java’s Built-in Exceptions
Creating our own Exception
subclasses
• // This program creates a custom exception type.
• class MyException extends Exception {
• private int detail;
• MyException(int a) {
• detail = a;
• }
• public String toString() {
• return "MyException[" + detail + "]";
• }
• }
• class ExceptionDemo {
• static void compute(int a) throws MyException {
• System.out.println("Called compute(" + a + ")");
Creating our own Exception
subclasses
• if(a > 10)
• throw new MyException(a);
• System.out.println("Normal exit");
• }
• public static void main(String args[]) {
• try {
• compute(1);
• compute(20);
• } catch (MyException e) {
• System.out.println("Caught " + e);
• }
• }
• }
• Called compute(1)
• Normal exit
• Called compute(20)
• Caught MyException[20]

More Related Content

What's hot

What is an exception in java?
What is an exception in java?What is an exception in java?
What is an exception in java?Pramod Yadav
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsMiquel Martin
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking frameworkPhat VU
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 

What's hot (13)

Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
 
Exceptions
ExceptionsExceptions
Exceptions
 
What is an exception in java?
What is an exception in java?What is an exception in java?
What is an exception in java?
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-Knows
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Using Mockito
Using MockitoUsing Mockito
Using Mockito
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 

Viewers also liked

Exception handling
Exception handlingException handling
Exception handlingTony Nguyen
 
Behaviour driven development
Behaviour driven developmentBehaviour driven development
Behaviour driven developmentTony Nguyen
 
CURRICULAM VITAE USMAN-1
CURRICULAM VITAE USMAN-1CURRICULAM VITAE USMAN-1
CURRICULAM VITAE USMAN-1Usman Amin
 
Can ho sai gon metro park
Can ho sai gon metro parkCan ho sai gon metro park
Can ho sai gon metro parkthuynhi media
 
ērnu un pusaudžu psihoemocionālā labklājība Latvijā: fakti un risinājumi. Tom...
ērnu un pusaudžu psihoemocionālā labklājība Latvijā: fakti un risinājumi. Tom...ērnu un pusaudžu psihoemocionālā labklājība Latvijā: fakti un risinājumi. Tom...
ērnu un pusaudžu psihoemocionālā labklājība Latvijā: fakti un risinājumi. Tom...BJPLC
 
Challenges in non Ebola healthcare facilities during an EVD outbreak
Challenges in non Ebola healthcare facilities during an EVD outbreakChallenges in non Ebola healthcare facilities during an EVD outbreak
Challenges in non Ebola healthcare facilities during an EVD outbreakGOAL Global
 
Inventory Accuracy Improvement Plan
Inventory Accuracy Improvement Plan Inventory Accuracy Improvement Plan
Inventory Accuracy Improvement Plan Akeia Dixon
 
Kā runāt ar bērnu par krīzes situācijām? BTAI krīzes tālruņa speciāliste Agit...
Kā runāt ar bērnu par krīzes situācijām? BTAI krīzes tālruņa speciāliste Agit...Kā runāt ar bērnu par krīzes situācijām? BTAI krīzes tālruņa speciāliste Agit...
Kā runāt ar bērnu par krīzes situācijām? BTAI krīzes tālruņa speciāliste Agit...BJPLC
 
Inese Millere, Stresa avoti bērnu un pusaudžu dzīvē. Dzīvesveida risinājumi.
Inese Millere, Stresa avoti bērnu un pusaudžu dzīvē. Dzīvesveida risinājumi.Inese Millere, Stresa avoti bērnu un pusaudžu dzīvē. Dzīvesveida risinājumi.
Inese Millere, Stresa avoti bērnu un pusaudžu dzīvē. Dzīvesveida risinājumi.BJPLC
 
Exception handling
Exception handlingException handling
Exception handlingTony Nguyen
 
Decision analysis
Decision analysisDecision analysis
Decision analysisTony Nguyen
 

Viewers also liked (20)

Memory caching
Memory cachingMemory caching
Memory caching
 
Exception handling
Exception handlingException handling
Exception handling
 
Html5
Html5Html5
Html5
 
Behaviour driven development
Behaviour driven developmentBehaviour driven development
Behaviour driven development
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
CURRICULAM VITAE USMAN-1
CURRICULAM VITAE USMAN-1CURRICULAM VITAE USMAN-1
CURRICULAM VITAE USMAN-1
 
Can ho sai gon metro park
Can ho sai gon metro parkCan ho sai gon metro park
Can ho sai gon metro park
 
ērnu un pusaudžu psihoemocionālā labklājība Latvijā: fakti un risinājumi. Tom...
ērnu un pusaudžu psihoemocionālā labklājība Latvijā: fakti un risinājumi. Tom...ērnu un pusaudžu psihoemocionālā labklājība Latvijā: fakti un risinājumi. Tom...
ērnu un pusaudžu psihoemocionālā labklājība Latvijā: fakti un risinājumi. Tom...
 
Challenges in non Ebola healthcare facilities during an EVD outbreak
Challenges in non Ebola healthcare facilities during an EVD outbreakChallenges in non Ebola healthcare facilities during an EVD outbreak
Challenges in non Ebola healthcare facilities during an EVD outbreak
 
Booleanos
BooleanosBooleanos
Booleanos
 
Inventory Accuracy Improvement Plan
Inventory Accuracy Improvement Plan Inventory Accuracy Improvement Plan
Inventory Accuracy Improvement Plan
 
Kā runāt ar bērnu par krīzes situācijām? BTAI krīzes tālruņa speciāliste Agit...
Kā runāt ar bērnu par krīzes situācijām? BTAI krīzes tālruņa speciāliste Agit...Kā runāt ar bērnu par krīzes situācijām? BTAI krīzes tālruņa speciāliste Agit...
Kā runāt ar bērnu par krīzes situācijām? BTAI krīzes tālruņa speciāliste Agit...
 
Inese Millere, Stresa avoti bērnu un pusaudžu dzīvē. Dzīvesveida risinājumi.
Inese Millere, Stresa avoti bērnu un pusaudžu dzīvē. Dzīvesveida risinājumi.Inese Millere, Stresa avoti bērnu un pusaudžu dzīvē. Dzīvesveida risinājumi.
Inese Millere, Stresa avoti bērnu un pusaudžu dzīvē. Dzīvesveida risinājumi.
 
Maven
MavenMaven
Maven
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception
ExceptionException
Exception
 
List in webpage
List in webpageList in webpage
List in webpage
 
Decision analysis
Decision analysisDecision analysis
Decision analysis
 
Game theory
Game theoryGame theory
Game theory
 
Reflection
ReflectionReflection
Reflection
 

Similar to Exception

L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .happycocoman
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptpromila09
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingraksharao
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - iiRavindra Rathore
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxARUNPRANESHS
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingPrabu U
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxVeerannaKotagi1
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAdil Mehmoood
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfKALAISELVI P
 

Similar to Exception (20)

L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Chapter v(error)
Chapter v(error)Chapter v(error)
Chapter v(error)
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
43c
43c43c
43c
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
Exceptionn
ExceptionnExceptionn
Exceptionn
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 

More from Tony Nguyen

Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisTony Nguyen
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceTony Nguyen
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningTony Nguyen
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningTony Nguyen
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryTony Nguyen
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksTony Nguyen
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheTony Nguyen
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesTony Nguyen
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsTony Nguyen
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileTony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaTony Nguyen
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsTony Nguyen
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaTony Nguyen
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonTony Nguyen
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonTony Nguyen
 

More from Tony Nguyen (20)

Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Cache recap
Cache recapCache recap
Cache recap
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Object model
Object modelObject model
Object model
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Inheritance
InheritanceInheritance
Inheritance
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 
Api crash
Api crashApi crash
Api crash
 

Recently uploaded

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Recently uploaded (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

Exception

  • 2. Exception • An exception is an abnormal condition that arises in a code sequence at run time. • An exception is a run time error
  • 3. • 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 • That method maychoose to handle it self or pass it on. • At some point the exception is caught and processed
  • 4. • Exceptions can be generated by java run time system or can be manually generated by your code. • JRE generates exceptions when you violate the rules of java language or the constraints of java execution environment. • Manually generated exceptions are typically used to report some error condition to the caller of a method.
  • 5. • 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 • If an exception occurs within the try block, it is thrown • Your code can catch this exception (using catch) and handle it
  • 6. • 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 absolutely must be executed before a method returns is put in a finally block
  • 7. • This is the general form of an exception-handling block: try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed before try block ends }
  • 8. Exception Types • All exception types are subclasses of the built-in class Throwable • Immediately below Throwable are two subclasses that partition exceptions into two distinct branches • One branch is headed by Exception • This class is used for exceptional conditions that user programs should catch
  • 9. • There is an important subclass of Exception, called RuntimeException • Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing
  • 10. • The other branch is topped by Error, which 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
  • 11. Uncaught Exceptions • class Exc0 { • public static void main(String args[]) { • int d = 0; • int a = 42 / d; • } • } • Java.lang.ArithmeticException: /by zero at Exc0.main(Exco.java:4)
  • 12. • When JRE detects the attempt to /0 it constrcucts a new exception object and throws this exception • This causes the execution of Exc0 to stop because once an exception is generated it should be caught some where.In this case we have not supplied any handler so default handler of JRE gets called. • Default handler displays string describing the exception and the stack trace from the point at which exception has occurred and terminates the program.
  • 13. • class Exc1 { • static void subroutine() { • int d = 0; • int a = 10 / d; • } • public static void main(String args[]) { • Exc1.subroutine(); • } • }
  • 14. • Java.lang.ArithmeticException: /by zero • at Exc1.subroutine(Exc1.java:4) • at Exc1.main(Exc1.java:7)
  • 15. Using try and catch • Handling an exception manually provides two benefits • First, it allows you to fix the error • Second, it prevents the program from automatically terminating
  • 16. class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } } o/p: This program generates the following output: Division by zero.
  • 17. • A try and its catch statement form a unit • The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement • A catch statement cannot catch an exception thrown by another try statement
  • 18. // Handle an exception and move on. import java.util.Random; class HandleError { public static void main(String args[]) { int a=0, b=0, c=0; Random r = new Random(); for(int i=0; i<32000; i++) { try { b = r.nextInt(); c = r.nextInt(); a = 12345 / (b/c); } catch (ArithmeticException e) { System.out.println("Division by zero."); a = 0; // set a to zero and continue } System.out.println("a: " + a); } } }
  • 19. Displaying a Description of an Exception catch (ArithmeticException e) { System.out.println("Exception: " + e); a = 0; // set a to zero and continue } Exception: java.lang.ArithmeticException: / by zero
  • 20. Multiple catch Clauses // Demonstrate multiple catch statements. class MultiCatch { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } System.out.println("After try/catch blocks."); } }
  • 21. • Java MultiCatch • a=0 • Divide by 0:java.lang.ArithmeticException:/by zero • After try/catch blocks OR • Java MultiCatch TestArg • a=1 • Array index oob:java.lang.ArrayIndexOutOfBoundsException:42 • After try/catch blocks
  • 22. /* This program contains an error. A subclass must come before its superclass in a series of catch statements. If not, unreachable code will be created and a compile- time error will result. */ class SuperSubCatch { public static void main(String args[]) { try { int a = 0; int b = 42 / a; } catch(Exception e) { System.out.println("Generic Exception catch."); } /* This catch is never reached because ArithmeticException is a subclass of Exception. */ catch(ArithmeticException e) { // ERROR - unreachable System.out.println("This is never reached."); } }
  • 23. Nested try Statements • Each time a try statement is entered, the context of that exception is pushed on the stack
  • 24. • // An example nested try statements. • class NestTry { • public static void main(String args[]) { • try { • int a = args.length; • /* If no command line args are present, • the following statement will generate • a divide-by-zero exception. */ • int b = 42 / a; • System.out.println("a = " + a); • try { // nested try block • /* If one command line arg is used, • then an divide-by-zero exception • will be generated by the following code. */
  • 25. • if(a==1) a = a/(a-a); // division by zero • /* If two command line args are used • then generate an out-of-bounds exception. */ • if(a==2) { • int c[] = { 1 }; • c[42] = 99; // generate an out-of-bounds exception • } • } catch(ArrayIndexOutOfBoundsException e) { • System.out.println("Array index out-of-bounds: " + e); • } • } catch(ArithmeticException e) { • System.out.println("Divide by 0: " + e); • } • } • }
  • 26. • /* Try statements can be implicitly nested via • calls to methods. */ • class MethNestTry { • static void nesttry(int a) { • try { // nested try block • /* If one command line arg is used, • then an divide-by-zero exception • will be generated by the following code. */ • if(a==1) a = a/(a-a); // division by zero • /* If two command line args are used • then generate an out-of-bounds exception. */ • if(a==2) { • int c[] = { 1 }; • c[42] = 99; // generate an out-of-bounds exception • } • } catch(ArrayIndexOutOfBoundsException e) {
  • 27. • System.out.println("Array index out-of-bounds: " + e); • } • } • public static void main(String args[]) { • try { • int a = args.length; • /* If no command line args are present, • the following statement will generate • a divide-by-zero exception. */ • int b = 42 / a; • System.out.println("a = " + a); • nesttry(a); • } catch(ArithmeticException e) { • System.out.println("Divide by 0: " + e); • } • } • }
  • 28. throw • It is possible for your program to throw an exception explicitly, using the throw statement • The general form of throw is shown here: throw ThrowableInstance;
  • 29. • Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable • There are two ways you can obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator • The flow of execution stops immediately after the throw statement; any subsequent statements are not executed
  • 30. // Demonstrate throw. class ThrowDemo { static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; // rethrow the exception } } public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } } Output: Caught inside demoproc. Recaught: java.lang.NullPointerException: demo
  • 31. 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 • A throws clause lists the types of exceptions that a method might throw
  • 32. • Exceptions that a method can throw must be declared in the throws clause • This is the general form of a method declaration that includes a throws clause: type method-name(parameter-list) throws exception-list { // body of method } • Here, exception-list is a comma-separated list of the exceptions that a method can throw
  • 33. // This program contains an error and will not compile. class ThrowsDemo { static void throwOne() { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[ ]) { throwOne(); } }
  • 34. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } Here is the output generated by running this example program: inside throwOne
  • 35. 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 • If an exception is thrown, the finally block will execute even if no catch statement matches the exception
  • 36. • The finally clause is optional • Each try statement requires at least one catch or a finally clause
  • 37. // Demonstrate finally. class FinallyDemo { // Through an exception out of the method. static void procA() { try { System.out.println("inside procA"); throw new RuntimeException("demo"); } finally { System.out.println("procA's finally"); } } // Return from within a try block. static void procB() { try { System.out.println("inside procB"); return; } finally { System.out.println("procB's finally"); } }
  • 38. // Execute a try block normally. static void procC() { try { System.out.println("inside procC"); } finally { System.out.println("procC's finally"); } } public static void main(String args[]) { try { procA(); } catch (Exception e) { System.out.println("Exception caught"); } procB(); procC(); } }
  • 39. Here is the output generated by the preceding program: inside procA procA’s finally Exception caught inside procB procB’s finally inside procC procC’s finally
  • 41.
  • 42.
  • 43. Creating our own Exception subclasses • // This program creates a custom exception type. • class MyException extends Exception { • private int detail; • MyException(int a) { • detail = a; • } • public String toString() { • return "MyException[" + detail + "]"; • } • } • class ExceptionDemo { • static void compute(int a) throws MyException { • System.out.println("Called compute(" + a + ")");
  • 44. Creating our own Exception subclasses • if(a > 10) • throw new MyException(a); • System.out.println("Normal exit"); • } • public static void main(String args[]) { • try { • compute(1); • compute(20); • } catch (MyException e) { • System.out.println("Caught " + e); • } • } • }
  • 45. • Called compute(1) • Normal exit • Called compute(20) • Caught MyException[20]