SlideShare a Scribd company logo
1 of 16
Errors - Exceptions
• Object describes an exceptional (that is, error) condition that has
occurred in a piece of code.
• An exception is an abnormal condition that arises in a code sequence at
run time.
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 after try block ends
}
Error=Run || Comple
• try{….}catch(typeofException){….}
• try{….}catch(….){….}…catch(..){….}
• try{….}catch(…){…}…catch(…){…}..finally{…}
– try=check error
– catch=detect error
– throw=making error occur
– throws=throw error.
– Finally=end of choice
Exception Types
• RuntimeException: subclass of Exception
– automatically defined for the programs that you
write and include things such as division by zero
and invalid array indexing.
• Error
– not expected to be caught under normal
circumstances by your program ;Stack overflow.
RuntimeException: execute
Erro: compile
class Except1{
public static void main(String args[])
{
int d, a;
try{
d=0;
a=13/d;
}catch(ArithmeticException e)
{
System.out.println("Cannot divided by 0 te." );
}
}}
Using try and catch
Multiple catch Clauses
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.");
}
}
throw
• Catching exceptions that are thrown by the Java run-time system.
• throw ThrowableInstance;
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);
}
}
}
=>
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
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);
}
}
}
throws
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
int a,b;
a=10;
b=0;
if(b==0)
{
throw new IllegalAccessException("Cannot divide by zerto te");
}
else
System.out.println(a + "/" + b + "=" + a/b);
}
public static void main(String args[])
{
try {
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught: " + e);
}}}
finally
// 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");
}
Java’s Built-in Exceptions
Rethrowing Exceptions
• if the handler cannot process the exception or simply wants to let
its caller be notified of the exception.
• try {
statements;}
catch (TheException ex) {
perform operations before exits;
throw ex;
}
Chained Exceptions
Creating Your Own Exception Subclasses

More Related Content

What's hot

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
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
UVM Driver sequencer handshaking
UVM Driver sequencer handshakingUVM Driver sequencer handshaking
UVM Driver sequencer handshakingHARINATH REDDY
 
From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017Agustin Ramos
 
Java2 days 2013-j-treg
Java2 days 2013-j-tregJava2 days 2013-j-treg
Java2 days 2013-j-tregMani Sarkar
 
GDG Madrid - Dart Event - By Iván Zaera
GDG Madrid - Dart Event - By Iván ZaeraGDG Madrid - Dart Event - By Iván Zaera
GDG Madrid - Dart Event - By Iván ZaeraJc Miñarro
 

What's hot (20)

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
 
Handling
HandlingHandling
Handling
 
Power mock
Power mockPower mock
Power mock
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
43c
43c43c
43c
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Unit testing
Unit testingUnit testing
Unit testing
 
41c
41c41c
41c
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
UVM Driver sequencer handshaking
UVM Driver sequencer handshakingUVM Driver sequencer handshaking
UVM Driver sequencer handshaking
 
Mock with Mockito
Mock with MockitoMock with Mockito
Mock with Mockito
 
From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017
 
Java2 days 2013-j-treg
Java2 days 2013-j-tregJava2 days 2013-j-treg
Java2 days 2013-j-treg
 
Loops in c
Loops in cLoops in c
Loops in c
 
GDG Madrid - Dart Event - By Iván Zaera
GDG Madrid - Dart Event - By Iván ZaeraGDG Madrid - Dart Event - By Iván Zaera
GDG Madrid - Dart Event - By Iván Zaera
 

Similar to Handle Errors and Exceptions in Java

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
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
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
 
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
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - iiRavindra Rathore
 

Similar to Handle Errors and Exceptions in Java (20)

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
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
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
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 

More from Chhom Karath

More from Chhom Karath (20)

set1.pdf
set1.pdfset1.pdf
set1.pdf
 
Set1.pptx
Set1.pptxSet1.pptx
Set1.pptx
 
orthodontic patient education.pdf
orthodontic patient education.pdforthodontic patient education.pdf
orthodontic patient education.pdf
 
New ton 3.pdf
New ton 3.pdfNew ton 3.pdf
New ton 3.pdf
 
ច្បាប់ញូតុនទី៣.pptx
ច្បាប់ញូតុនទី៣.pptxច្បាប់ញូតុនទី៣.pptx
ច្បាប់ញូតុនទី៣.pptx
 
Control tipping.pptx
Control tipping.pptxControl tipping.pptx
Control tipping.pptx
 
Bulbous loop.pptx
Bulbous loop.pptxBulbous loop.pptx
Bulbous loop.pptx
 
brush teeth.pptx
brush teeth.pptxbrush teeth.pptx
brush teeth.pptx
 
bracket size.pptx
bracket size.pptxbracket size.pptx
bracket size.pptx
 
arch form KORI copy.pptx
arch form KORI copy.pptxarch form KORI copy.pptx
arch form KORI copy.pptx
 
Bracket size
Bracket sizeBracket size
Bracket size
 
Couple
CoupleCouple
Couple
 
ច្បាប់ញូតុនទី៣
ច្បាប់ញូតុនទី៣ច្បាប់ញូតុនទី៣
ច្បាប់ញូតុនទី៣
 
Game1
Game1Game1
Game1
 
Shoe horn loop
Shoe horn loopShoe horn loop
Shoe horn loop
 
Opus loop
Opus loopOpus loop
Opus loop
 
V bend
V bendV bend
V bend
 
Closing loop
Closing loopClosing loop
Closing loop
 
Maxillary arch form
Maxillary arch formMaxillary arch form
Maxillary arch form
 
Front face analysis
Front face analysisFront face analysis
Front face analysis
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Recently uploaded (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 

Handle Errors and Exceptions in Java

  • 2. • Object describes an exceptional (that is, error) condition that has occurred in a piece of code. • An exception is an abnormal condition that arises in a code sequence at run time. 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 after try block ends }
  • 3. Error=Run || Comple • try{….}catch(typeofException){….} • try{….}catch(….){….}…catch(..){….} • try{….}catch(…){…}…catch(…){…}..finally{…} – try=check error – catch=detect error – throw=making error occur – throws=throw error. – Finally=end of choice
  • 4. Exception Types • RuntimeException: subclass of Exception – automatically defined for the programs that you write and include things such as division by zero and invalid array indexing. • Error – not expected to be caught under normal circumstances by your program ;Stack overflow.
  • 6. class Except1{ public static void main(String args[]) { int d, a; try{ d=0; a=13/d; }catch(ArithmeticException e) { System.out.println("Cannot divided by 0 te." ); } }} Using try and catch
  • 7. Multiple catch Clauses 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."); } }
  • 8. throw • Catching exceptions that are thrown by the Java run-time system. • throw ThrowableInstance; 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); } } } => Caught inside demoproc. Recaught: java.lang.NullPointerException: demo
  • 9. 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); } } }
  • 10. throws class ThrowsDemo { static void throwOne() throws IllegalAccessException { int a,b; a=10; b=0; if(b==0) { throw new IllegalAccessException("Cannot divide by zerto te"); } else System.out.println(a + "/" + b + "=" + a/b); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught: " + e); }}}
  • 11. finally // 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"); }
  • 13.
  • 14. Rethrowing Exceptions • if the handler cannot process the exception or simply wants to let its caller be notified of the exception. • try { statements;} catch (TheException ex) { perform operations before exits; throw ex; }
  • 16. Creating Your Own Exception Subclasses