Sie sind auf Seite 1von 57

Java Exceptions and Collections

Course Software in Electronics and Telecommunications English classes

Overview
Errors and exceptions in Java Main exception instructions Class exceptions hierarchy User exceptions Packages and Exceptions Assertions Java Collections Collections Without Generics Collections Interfaces
2

Types of Errors
An error indicates that there is a problem with interpreting your program. There are three types of errors: Syntax Errors Logic Errors Exceptions (Run-Time Errors)

Syntax Errors
An error can occur when a file is compiled. These errors are coding or syntax errors, such as missing semicolons, spelling errors, trying to assign a value to a variable that is not the correct type, etc. It is common to go through several rounds of fixing syntax errors before compiling the file is successful.
4

Forgetting a semicolon at the end of a java statement is a syntax error.


Exception in thread "main" java.lang.Error:Unresolved

compilation problem:Syntax error, insert ";" to complete Statement at ErrorIndicators.main(ErrorIndicators.java:8)

Using = instead of == to compare values in an if condition is a syntax error. if(x=y) if(x==y)

Logic Errors
Logic errors occur as a result of programmer logic that is incorrect. These errors do not produce a compile or runtime error. Use de debugger in this case if it is difficult to see the error. For example, a loop runs too many times, or the program produces incorrect output. Placing a semicolon after an if condition, or after a loop statement:
Interpreters read the semicolon as the end of the loop, which means that everything after the semicolon will be treated as outside of the loop.

for(int i = 0; i < 5; i++); System.out.println(i);

Java Exceptions
An exception is given by a condition that appears during the execution of a Java application. The program must: - stop, an error will occur - process an exception Exceptions as a response to an error condition: -divide by zero an integer -out of domain range for a variable -out of array range dimensions, etc.
7

-Exceptions are generated automatically from a garde zone at run-time, or by the programmer with a throw instruction -When the interpreter will manage an exception, an exception object will be generated that will store the application state -An exception handler will specify where the exception will be processed, otherwise the application will be stopped
8

Once a file compiles successfully, an error can occur when a file is being tested during run time. These run-time errors that are called exceptions should be handled by the programmer using code in the program. The correct terminology is that the code will throw an exception. Java exceptions fall into two categories: Unchecked Exceptions Checked Exceptions, most of which originate in programs with Input/Output (IO) Both checked and unchecked Exceptions can be handled by creating a try/catch block.
9

Unchecked Exceptions
It is optional to handle unchecked exceptions in Java. However, if the unchecked exception is not handled by the programmer, and an error occurs, the program will crash. Common unchecked exceptions: IndexOutofBoundsException NullPointer exception
10

NullPointer Exception
The following code will throw a NullPointer Exception. Why?
StringBuilder[] sb1 = new StringBuilder[5]; sb1[0].append(Hello);
The StringBuilder objects in the array have not been initialized. To correct the problem:

for(int i = 0; i<sb1.length; i++){ sb1[i] = new StringBuilder(); }


11

Checked exceptions
FileNotFoundException is an IO exception. IO exceptions are checked exceptions. Most checked exceptions come from using I/O classes. Checked exceptions MUST be handled. The programmer can use a try/catch block to handle checked exceptions OR use a throws statement in the method declaration to pass the treatment up in hierarchy.

12

Main exception instructions:


1. throw throw (referinta_la_obiect_clsThrowable) ; throw new ArithmeticException(); or, Exception oe= new Exception(); throw oe;

13

If you throw an exception, your interpreter will stop running the program at that point, which indicates to the user that they have reached the exception. In code you would throw an exception like this: throw new Exception(Array index + i + is

out of bounds!);

14

2. try, catch, finally try{ declaratii si instructiuni; // garde zone... } catch(clsThrowable ref_oe) {instructiuni;} [catch(clsThrowable ref_oe) {instructiuni;}] [finally{ instructiuni; }]
15

Using a try/catch block to handle an I/O exception: try{ FileReader reader = new FileReader(test.txt); } catch(IOException e){ System.out.println(File not found); }
16

This is an example of handling an IndexOutOfBoundsException with a try/catch block:


try{ //i is the index of an array with length 10 if(i > 9 || i < 0) throw new Exception(Index + i + is out of bounds!); } catch(Exception e){

//This code will run only if the exception was thrown if(i > 9) i-=9; else i+=9; } //You may have additional code here that will run only if the exception was not thrown

17

3. throws, to pass up in hierarchy the treatment


tip_val_ret nume_metoda(lista_param) [throws tip_clsExceptie] { [instructiuni;] } It is possible to use a throw instruction in a catch() and the throws will pass the treatment up in hierarchy
18

Using a throws statement to handle an

IOException:

public static void main(String[] args) throws IOException{ FileReader reader = new FileReader(test.txt); }

The throws statement handles the exception, however, this program will crash if an error occurs that throws an exception!

19

Class exceptions hierarchy

java.lang.Throwable

java.lang.Exception

java.lang.Error

Excepii specifice

java.lang.RuntimeException

Erori

Exceptii la rulare

20

It is possible to have default handler for exceptions managed by the system not by the programmer It is possible to have nested try instructions From jdk 1.4 we have chained exceptions, to associate an exception to other that is thrown (Ex. The cause of NullPointerException is an ArithmeticException)
21

import java.io.*; public class Exceptii { public static void main(String[] args) { int i,sum=0; int sir[]=new int[10]; DataInputStream in=new DataInputStream(System.in); try{ System.out.println("Introduceti elementele sirului:"); for(i=0;i<10;i++){ System.out.print("elementul "+i+": "); sir[i]=Integer.parseInt(in.readLine()); }//for System.out.println("Suma elementelor sirului este: "); for(i=0;i<12;i++) sum+=sir[i]; }//try
22

catch(IOException ioe){ System.out.println("Exceptie la citire."); System.out.println(ioe.toString()); System.exit(1); }//catch IOException catch(ArrayIndexOutOfBoundsException ae){ System.out.println("Exceptie de index."); System.out.println ("Suma ="+sum); System.out.println(ae.toString()); System.exit(1); }//catch ArrayIndexOutOfBoundsException }//met. main }//class_Exceptii
Result:

Suma elementelor sirului este: Exceptie de index. Suma =47 java.lang.ArrayIndexOutOfBoundsException: 10

23

// Sortarea unui sir cu metoda bulelor import java.util.*; import java.io.DataInputStream; import java.lang.String; import java.io.IOException; class Buble { public static void main(String args[]){ int n,aux,i; boolean ok; int S[]=new int[7]; DataInputStream dis = new DataInputStream(System.in); String numStr = null; try { System.out.flush(); // Citire numar de elemente ale sirului System.out.println("Introduceti numrul maxim de elemente (<7): \n"); numStr = dis.readLine(); n = Integer.parseInt(numStr); // Citirea elementelor System.out.println("Introduceti elementele: \n"); for(i=0;i<n;i++){ numStr = dis.readLine(); S[i] = Integer.parseInt(numStr); }
24

// Metoda bulelor do { ok=true; for(i=0;i<n-1;i++){ if(S[i]>S[i+1]){ ok=false; aux=S[i]; S[i]=S[i+1]; S[i+1]=aux; } } } while(!ok); // Afisarea sirului ordonat System.out.println(Sirul ordonat crescator este: \n\n"); for(i=0;i<n;i++) System.out.println("Sirul este: "+S[i]); } catch (IOException ioe){ System.out.println(ioe.toString()); System.exit(1); } }// end main }// end class Buble
25

package exc1;

public class exc1 {public static void main (String[] args) { System.out .println("\n*** Exception exemplif ***\n\n"); try{ throw new Exception ("Aceasta este o exceptie"); }catch(Exception e){ System.out .println("Caught Exception"); System.out .println("e.getMessage(): "+e.getMessage()); System.out .println("e.toString(): "+e.toString ()); System.out .println("e.printStackTrace():"); e.printStackTrace(); System.out .println("\n* Exception Results\n"); }//end catch System.out .print("\nApasati <Enter> pentru terminare..."); try{char a=(char) System.in.read(); }catch(java.io.IOException nume_excep){}}//end main }//end class
26

*** Exception exemplif ***

Caught Exception e.getMessage(): Aceasta este o exceptie e.toString(): java.lang.Exception: Aceasta este o exceptie e.printStackTrace(): java.lang.Exception: Aceasta este o exceptie

* Exception Results

Apasati <Enter> pentru terminare...at

exc1.exc1.main(exc1.java:7)

27

User exceptions
import java.lang.Throwable; //clasa proprie pt. tratarea exceptiilor class MyException extends Throwable{ //constructor public MyException(){ //apelul constructorului clasei de baza super(Sirul de caractere nu are voie sa fie abc!!!"); } }
28

//o clasa care foloseste exceptiile proprii class X{ void metoda(String text) throws MyException{ //se lanseaza o exceptie daca sirul este egal cu "abc" if(text.equalsIgnoreCase("abc")){ //lansarea unei instante anonime de tip MyException throw new MyException(); } else{ System.out.println(Sirul de caractere "+text+"

corespunde."); } }

}
29

class Test{ public static void main(String args[]){ String text_interzis = new String("abc"); String text_acceptat = new String("xyz"); X ob1 = new X(); try{ ob1.metoda(text_interzis); } catch(MyException ex1){ ex1.printStackTrace(); } try{ ob1.metoda(text_acceptat); } catch(MyException ex2){ ex2.toString(); } } }
30

import java.lang.Exception; class }

ResultTooLarge extends Exception { ResultTooLarge(String msg) { super(msg); }

31

class TestExceptions { public static void main(String args[]) { int a=100, b=2; try { int result = a/b; if (result > 5) throw new ResultTooLarge(result + " is too Large."); } catch (ResultTooLarge e) { System.out.println("Caught the result too large."); System.out.println(e.getMessage()); } finally { System.out.println("Finally will always be run."); System.out.println("Even if exceptions are caught."); } } }
32

Packages and Exceptions


import Calin.Citeste; class Lanseaza{ public void Imparte(String intro, String intra) throws ArithmeticException, Exception { int x=Integer.parseInt(intro); int y=Integer.parseInt(intra); if(y==0)throw new Exception ("din clasa Lanseaza"); else { float g=(float)x/y; System.out.println("rezultatul este "+g); } }//Imparte

33

public static void main(String args[]){ String tttt; String yyyy; Citeste ab=new Citeste(); System.out.println("Introdu doua numere intregi: "); tttt=ab.CitesteTastatura(); yyyy=ab.CitesteTastatura(); try{ Lanseaza ob=new Lanseaza(); ob.Imparte(tttt,yyyy); } catch(Exception tt){ System.out.println("Exceptia este prinsa in metoda main() fara a

face alta actiune"); finally{ System.out.println("S-a sfarsit aplicatia"); }//main } //class Lanseaza

34

Assertions
Assertions are a form of testing that allow you to check for correct assumptions throughout your code. For example: If you assume that your method will calculate a negative value, you can use an assertion. Assertions can be used to check internal logic of a single method: Internal invariants Control flow invariants Class invariants

Assertions can be disabled at run time; therefore: Do not use assertions to check parameters. Do not use methods that can cause side effects in an assertion check.
35

Assertion Syntax
There are two different assertion statements: assert <boolean_expression> ; assert <boolean_expression> : <detail_expression> ; If the <boolean_expression> evaluates as false, then an AssertionError is thrown. A second argument is optional, but can be declared and will be converted to a string to serve as a description to the AssertionError message displayed.

36

Internal Invariants
Internal invariants are testing values and evaluations in your methods. if (x > 0) { // do this } else { assert ( x == 0 ); // do that // what if x is negative? }

37

Control Flow Invariants


Assertions can be made inside control flow statements such as shown below. These are called control flow invariants.

switch (suit) { case Suit.CLUBS: // ... break; case Suit.DIAMONDS: // ... break; case Suit.HEARTS: // ... break; case Suit.SPADES: // ... break; default: assert false : "Unknown playing card suit"; break; }

38

Class Invariants
A class invariant is an invariant used to evaluate the assumptions of the class instances, which is an Object in the following example: public Object pop() { int size = this.getElementCount(); if (size == 0) { throw new RuntimeException("Attempt to pop from empty

stack"); } Object result = /* code to retrieve the popped element */ ; // test the postcondition assert (this.getElementCount() == size - 1); return result; }
39

Java Collections
In Java we have classes and interfaces to manage lists and collections A collection is a group of objects, from Object class (ordered or not). It is possible to insert, sort, search, etc. It is possible to have different types of objects in a collection, or same type
40

A collection is an interface in the java.util package that is used to define a group, or collection, of objects. It includes sets, lists and map. Because it is in the java.util package, it will be necessary to import the java.util package into any programs you write using a collection. Collections are a very important part of data storing.

41

Collections Without Generics


Some ground rules for collections: The items must be accessible (this typically means that the class contains a method that sets the value of the item and a method that gets [or returns] the value of the item). Every object in the collection is of the same type. The items are not primitive types, if they were, an array would be sufficient in collecting them. The next slide contains sample code for a class PlayingCards that represents a collection interface of a typical deck of playing cards through arrays that contain a value for each card and the suit for each card.

42

43

Another way to build a collection interface is to use an object that already exists. Rather than creating and keeping track of the value and suit of each card, we can simply keep track of the cards. If we store the value and suit inside the class Card, any Card object will contain them, which is why it eliminates the need to use them in the Collections interface class.

44

45

Collection interfaces
No class offered by Java, but Collection interface is inherited by other interfaces such as: BeanContext, BeanContextServices, List, Set and SortedSet. List interface control an ordered collection of objects. Accepts duplicate objects Classes that implement that interface:AbstractList, ArrayList,

LinkedList, Vector

46

47

public interface Collection { // Metode cu caracter general int size(); boolean isEmpty(); void clear(); Iterator iterator(); // Operatii la nivel de element boolean contains(Object element); boolean add(Object element); boolean remove(Object element); // Operatii la nivel de multime boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); // Metode de conversie in vector Object[] toArray(); Object[] toArray(Object a[]); }
48

Set interface, no duplicate objects Classes that implement the interface: AbstractSet HashSet LinkedHashSet TreeSet

49

SortedSet
Natural order or given by a comparator. For any o1, o2, the call: o1.compareTo(o2) (or comparator.compare(o1, o2)) must be valid

50

public interface SortedSet extends Set { // Subliste SortedSet subSet(Object fromElement, Object toElement); SortedSet headSet(Object toElement); SortedSet tailSet(Object fromElement); // Capete Object first(); Object last(); Comparator comparator(); }
51

List- indexed elements


public interface List extends Collection { // Acces pozitional Object get(int index); Object set(int index, Object element); void add(int index, Object element); Object remove(int index); abstract boolean addAll(int index, Collection c); // Cautare int indexOf(Object o); int lastIndexOf(Object o); // Iterare ListIterator listIterator(); ListIterator listIterator(int index); // Extragere sublista List subList(int from, int to); }

52

Map interface will use an association Key/Value (Object). The key is unique. The association is:
-depending on key -depending on values -depending the association key/value

53

public interface Map { // Metode cu caracter general ... // Operatii la nivel de element Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); // Operatii la nivel de multime void putAll(Map t); // Vizualizari ale colectiei public Set keySet(); public Collection values(); public Set entrySet(); }
54

Classes that implements Map interface: AbstractMap Attributes HashMap Hashtable IdentityHashMap RenderingHints TreeMap WeakHashMap
55

SortedMap natural or comparator sort


public interface SortedMap extends Map { // Extragerea de subtabele SortedMap subMap(Object fromKey, Object toKey); SortedMap headMap(Object toKey); SortedMap tailMap(Object fromKey); // Capete Object first(); Object last(); // Comparatorul folosit pentru ordonare Comparator comparator(); }
56

Common Characteristics
-allows null element -are serializable -clone() method is defined -toString() method is defined -allows to create iterators -have explicit empty constructors and constructors with collections as parameters
57

Das könnte Ihnen auch gefallen