SlideShare a Scribd company logo
1 of 18
Java. Exception
IT Academy
07/17/2014
Agenda
▪Exception in Java
▪Exception Class Hierarchy
▪Exception Handling
▪Statements throws and throw
▪Several Exceptions
▪Creating own Exception
▪Case studies
Exception in Java
▪ Exceptions or exceptional situations (states) are the errors that
occurred in the program while it is running
//
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int k = Integer.parseInt(br.readLine()); // ???
//
int i = 4;
int j = 0
System.out.println("Result: "+ (i/j)); // ???
//
int[ ] a = new int[2];
a[2] = 0; // ???
Exception Class Hierarchy
Exception Class Hierarchy
▪ Exceptions are the result of problems in the program.
▪ Errors represent more serious problems associated with the
JVM-level problems.
▪ Exceptions are divided into three types:
– Checked exceptions;
– Unchecked exceptions, include Errors;
– RuntimeExceptions, a subclass of Exception.
▪ Checked exceptions are errors that can and should be handled
in the program.
– This type includes all subclasses of Exception (but not
RuntimeException).
▪ Unchecked exceptions does not require mandatory handling.
Exception Handling
try {
// Malicious code
} catch (SameExceptionType1 e1) {
// Exception handling for the class SameExaptionType1
} catch (SameExceptionType2 e2) {
// Exception handling for the class SameExaptionType2
} catch (Exception allAnotherExceptions) {
// Handle all exceptions previously untreated
} catch (Throwable allAnotherErrorsAndExceptions) {
/* Process all errors and exceptions that have not been
treated so far. Bad because it also handled Error-classes. */
} finally {
// Is performed in any case.
}
Exception Handling
▪ For Example (Unchecked exceptions)
int void doSomthing(int n) {
try {
// If n = 0, then causes ArithmeticException.
return 100 / n;
} catch (ArithmeticException e) {
// catch exception by class name.
System.out.println("Division by zero");
return 0;
}
}
Statement throws
▪ If a method can throw an exception, which he does not
handle, it must specify this behavior so that the calling code it
could take care of this exception.
▪ To this is added to the design throws, which lists the types of
exceptions.
– Except Error, RuntimeException, and their subclasses.
Statement throws
▪ For Example (Checked exceptions)
public void work(int i) throws InterruptedException {
Thread.sleep(1000); }
public void work(int i) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO catch block.
e.printStackTrace(); } }
public String getJson()
throws MalformedURLException, IOException { … }
Statement throw
▪ You can create your own exceptions using the throw
statement
try {
MyClass myClass = new MyClass();
if (myClass == null) {
throw new NullPointerException("Messages");
}
} catch (NullPointerException e) {
// TODO
e.printStackTrace();
System.out.println(e.getMessage());
}
Several Exceptions
▪ Code fragment may contain several problem places.
▪ For example, except for division by zero error is possible array
indexing.
▪ Need to create two or more operators catch for each type of
exception.
– They are checked in order.
– If an exception is detected at the first processing unit, it
will be executed, and the remaining checks will be skipped.
▪ If using multiple operators catch handlers subclasses
exceptions should be higher than their handlers superclasses.
Several Exceptions
try {
FileInputStream inFile=new FileInputStream("C:data.txt");
int bytesAvailable=inFile.available();
System.out.println("Bytes count: "+bytesAvailable+" Bytes");
byte[] r=new byte[10];
int count = inFile.read(r,0,bytesAvailable);
System.out.println("Was readed: "+count+" bytes.");
inFile.close();
System.out.println("Input stream closed.");
} catch (FileNotFoundException e) {
System.out.println("File Read/Write Error"+e.toString());
} catch (IOException e) {
System.out.println("I/O Error: "+e.toString()); }
Several Exceptions
int[] mas = {-1, 0, 1};
int i = 1;
Scanner sc = new Scanner(System.in);
try {
i = sc.nextInt();
mas[i-1] = 4 / i;
System.out.println(mas[i]);
} catch (ArithmeticException e) { // TODO
System.out.println("Invalid arithmetic operation");
} catch (ArrayIndexOutOfBoundsException e) { // TODO
System.out.println(“Index out of range");
} catch (Exception e) { // TODO
System.out.println("Some exception");
}
Creating own Exception
▪ Checked exception – MyException
// Creation subclass with two constructors
class MyException extends Exception {
// Classic constructor with a message of error
public MyException(String msg) {
super(msg);
}
// Empty constructor
public MyException() { }
}
Creating own Exception
public class ExampleException {
static void doSomthing(int n) throws MyException {
if (n > 0) {
int a = 100 / n;
} else {
// Creation and call exemption
throw new MyException("input value is below zero!");
} }
public static void main(String[] args) {
try { // try / catch block is required
doSomthing(-1);
} catch (MyException e1) {
System.err.print(e1);
} } }
Creating own Exception
▪ If you create your own exception class from
RuntimeException exception specification in the procedure
not necessary to write.
class MyException extends RuntimeException {}
public class ExampleException {
static void doSomthing(int n) {
throw new MyException();
}
public static void main(String[] args) {
DoSomthing(-1); // try / catch do not use
}
}
Creating own Exception
try {
FileInputStream inFile=new FileInputStream("C:data.txt");
// TODO
} catch (FileNotFoundException e) {
System.out.println("File Read/Write Error"+e.toString());
throw new MyException();
} catch (Exception e) {
System.out.println("I/O Error: "+e.toString());
throw new MyException(); }
▪ Some Exceptions do not required specification in the method
signature
– For Example, AritntetichEsseption, NullpointerException,
ArrayIndexOutOfBoundsException, etc.
Exception

More Related Content

What's hot

Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
exception handling in java
exception handling in java exception handling in java
exception handling in java aptechsravan
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptionsmyrajendra
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaARAFAT ISLAM
 
Exceptionhandling
ExceptionhandlingExceptionhandling
ExceptionhandlingNuha Noor
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 

What's hot (20)

Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
 
Java exception
Java exception Java exception
Java exception
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handling Exception handling
Exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
exception handling
exception handlingexception handling
exception handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 

Similar to Exception

Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Java_Exception-CheatSheet_Edureka.pdf
Java_Exception-CheatSheet_Edureka.pdfJava_Exception-CheatSheet_Edureka.pdf
Java_Exception-CheatSheet_Edureka.pdfFurkan Furkan
 
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
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Session 12 - Exception Handling - Part 1
Session 12 - Exception Handling - Part 1Session 12 - Exception Handling - Part 1
Session 12 - Exception Handling - Part 1PawanMM
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
Exception Handling.pdf
Exception Handling.pdfException Handling.pdf
Exception Handling.pdflsdfjldskjf
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
1.12 Exception Handing.pptx
1.12 Exception Handing.pptx1.12 Exception Handing.pptx
1.12 Exception Handing.pptxYashiUPADHYAY6
 
Exception Handling - Part 1
Exception Handling - Part 1 Exception Handling - Part 1
Exception Handling - Part 1 Hitesh-Java
 

Similar to Exception (20)

java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Java_Exception-CheatSheet_Edureka.pdf
Java_Exception-CheatSheet_Edureka.pdfJava_Exception-CheatSheet_Edureka.pdf
Java_Exception-CheatSheet_Edureka.pdf
 
Satish training ppt
Satish training pptSatish training ppt
Satish training ppt
 
Exception handling
Exception handlingException handling
Exception handling
 
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 handling
Exception handlingException handling
Exception handling
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Session 12 - Exception Handling - Part 1
Session 12 - Exception Handling - Part 1Session 12 - Exception Handling - Part 1
Session 12 - Exception Handling - Part 1
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling.pdf
Exception Handling.pdfException Handling.pdf
Exception Handling.pdf
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
1.12 Exception Handing.pptx
1.12 Exception Handing.pptx1.12 Exception Handing.pptx
1.12 Exception Handing.pptx
 
Exception Handling - Part 1
Exception Handling - Part 1 Exception Handling - Part 1
Exception Handling - Part 1
 

Recently uploaded

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 

Recently uploaded (20)

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 

Exception

  • 2. Agenda ▪Exception in Java ▪Exception Class Hierarchy ▪Exception Handling ▪Statements throws and throw ▪Several Exceptions ▪Creating own Exception ▪Case studies
  • 3. Exception in Java ▪ Exceptions or exceptional situations (states) are the errors that occurred in the program while it is running // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int k = Integer.parseInt(br.readLine()); // ??? // int i = 4; int j = 0 System.out.println("Result: "+ (i/j)); // ??? // int[ ] a = new int[2]; a[2] = 0; // ???
  • 5. Exception Class Hierarchy ▪ Exceptions are the result of problems in the program. ▪ Errors represent more serious problems associated with the JVM-level problems. ▪ Exceptions are divided into three types: – Checked exceptions; – Unchecked exceptions, include Errors; – RuntimeExceptions, a subclass of Exception. ▪ Checked exceptions are errors that can and should be handled in the program. – This type includes all subclasses of Exception (but not RuntimeException). ▪ Unchecked exceptions does not require mandatory handling.
  • 6. Exception Handling try { // Malicious code } catch (SameExceptionType1 e1) { // Exception handling for the class SameExaptionType1 } catch (SameExceptionType2 e2) { // Exception handling for the class SameExaptionType2 } catch (Exception allAnotherExceptions) { // Handle all exceptions previously untreated } catch (Throwable allAnotherErrorsAndExceptions) { /* Process all errors and exceptions that have not been treated so far. Bad because it also handled Error-classes. */ } finally { // Is performed in any case. }
  • 7. Exception Handling ▪ For Example (Unchecked exceptions) int void doSomthing(int n) { try { // If n = 0, then causes ArithmeticException. return 100 / n; } catch (ArithmeticException e) { // catch exception by class name. System.out.println("Division by zero"); return 0; } }
  • 8. Statement throws ▪ If a method can throw an exception, which he does not handle, it must specify this behavior so that the calling code it could take care of this exception. ▪ To this is added to the design throws, which lists the types of exceptions. – Except Error, RuntimeException, and their subclasses.
  • 9. Statement throws ▪ For Example (Checked exceptions) public void work(int i) throws InterruptedException { Thread.sleep(1000); } public void work(int i) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO catch block. e.printStackTrace(); } } public String getJson() throws MalformedURLException, IOException { … }
  • 10. Statement throw ▪ You can create your own exceptions using the throw statement try { MyClass myClass = new MyClass(); if (myClass == null) { throw new NullPointerException("Messages"); } } catch (NullPointerException e) { // TODO e.printStackTrace(); System.out.println(e.getMessage()); }
  • 11. Several Exceptions ▪ Code fragment may contain several problem places. ▪ For example, except for division by zero error is possible array indexing. ▪ Need to create two or more operators catch for each type of exception. – They are checked in order. – If an exception is detected at the first processing unit, it will be executed, and the remaining checks will be skipped. ▪ If using multiple operators catch handlers subclasses exceptions should be higher than their handlers superclasses.
  • 12. Several Exceptions try { FileInputStream inFile=new FileInputStream("C:data.txt"); int bytesAvailable=inFile.available(); System.out.println("Bytes count: "+bytesAvailable+" Bytes"); byte[] r=new byte[10]; int count = inFile.read(r,0,bytesAvailable); System.out.println("Was readed: "+count+" bytes."); inFile.close(); System.out.println("Input stream closed."); } catch (FileNotFoundException e) { System.out.println("File Read/Write Error"+e.toString()); } catch (IOException e) { System.out.println("I/O Error: "+e.toString()); }
  • 13. Several Exceptions int[] mas = {-1, 0, 1}; int i = 1; Scanner sc = new Scanner(System.in); try { i = sc.nextInt(); mas[i-1] = 4 / i; System.out.println(mas[i]); } catch (ArithmeticException e) { // TODO System.out.println("Invalid arithmetic operation"); } catch (ArrayIndexOutOfBoundsException e) { // TODO System.out.println(“Index out of range"); } catch (Exception e) { // TODO System.out.println("Some exception"); }
  • 14. Creating own Exception ▪ Checked exception – MyException // Creation subclass with two constructors class MyException extends Exception { // Classic constructor with a message of error public MyException(String msg) { super(msg); } // Empty constructor public MyException() { } }
  • 15. Creating own Exception public class ExampleException { static void doSomthing(int n) throws MyException { if (n > 0) { int a = 100 / n; } else { // Creation and call exemption throw new MyException("input value is below zero!"); } } public static void main(String[] args) { try { // try / catch block is required doSomthing(-1); } catch (MyException e1) { System.err.print(e1); } } }
  • 16. Creating own Exception ▪ If you create your own exception class from RuntimeException exception specification in the procedure not necessary to write. class MyException extends RuntimeException {} public class ExampleException { static void doSomthing(int n) { throw new MyException(); } public static void main(String[] args) { DoSomthing(-1); // try / catch do not use } }
  • 17. Creating own Exception try { FileInputStream inFile=new FileInputStream("C:data.txt"); // TODO } catch (FileNotFoundException e) { System.out.println("File Read/Write Error"+e.toString()); throw new MyException(); } catch (Exception e) { System.out.println("I/O Error: "+e.toString()); throw new MyException(); } ▪ Some Exceptions do not required specification in the method signature – For Example, AritntetichEsseption, NullpointerException, ArrayIndexOutOfBoundsException, etc.