c3 4 java-exceptions-collections 2013

Upload: rusu-vasile

Post on 04-Jun-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    1/57

    Java Exceptions and

    Collections

    Course Software in Electronics andTelecommunications English classes

    1

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    2/57

    OverviewErrors and exceptions in Java

    Main exception instructions

    Class exceptions hierarchy

    User exceptions

    Packages and Exceptions

    Assertions

    Java CollectionsCollections Without Generics

    Collections Interfaces

    2

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    3/57

    Types of Errors

    An error indicates that there is a problemwith interpreting your program.

    There are three types of errors: Syntax Errors

    Logic Errors

    Exceptions (Run-Time Errors)

    3

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    4/57

    Syntax Errors

    An error can occur when a file iscompiled. These errors are codingorsyntax errors, such as missing semi-

    colons, spelling errors, trying to assign avalue to a variable that is not the correcttype, etc.

    It is common to go through severalrounds of fixing syntax errors beforecompiling the file is successful.

    4

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    5/57

    Forgetting a semicolon at the end of a javastatement is a syntax error.

    Exception in thread "main" java.lang.Error:Unresolvedcompilation problem:Syntax error, insert ";" to completeStatement at ErrorIndicators.main(ErrorIndicators.java:8)

    Using =instead of ==to compare valuesin an ifcondition is a syntax error.

    if(x=y) if(x==y)

    5

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    6/57

    Logic ErrorsLogic errors occur as a result of programmer

    logic that is incorrect. These errors do not

    produce a compile or runtime error. Use dedebugger in this case if it is difficult to see theerror.

    For example, a loop runs too many times, or theprogram produces incorrect output.

    Placing a semicolon after an ifcondition, or aftera loop statement:

    Interpreters read the semicolon as the end of the loop,which means that everything after the semicolon will betreated as outside of the loop.

    for(int i = 0; i < 5; i++);

    System.out.println(i); 6

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    7/57

    Java Exceptions

    An exception is given by a condition thatappears during the execution of a Javaapplication.

    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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    8/57

    -Exceptions are generated automaticallyfrom a garde zone at run-time, or by the

    programmer with a throwinstruction-When the interpreter will manage an

    exception, an exception objectwill be

    generated that will store the applicationstate

    -An exception handlerwill specify where

    the exception will be processed, otherwisethe application will be stopped

    8

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    9/57

    Once a file compiles successfully, an error canoccur when a file is being tested during run time.

    These run-time errors that are called exceptionsshould be handled by the programmer using codein 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 inprograms with Input/Output (IO)

    Both checked and unchecked Exceptions can behandled by creating a try/catchblock.

    9

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    10/57

    Unchecked xceptionsIt is optional to handle unchecked exceptions

    in Java.

    However, if the unchecked exception is nothandled by the programmer, and an erroroccurs, the program will crash.

    Common unchecked exceptions:

    IndexOutofBoundsException

    NullPointerexception

    10

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    11/57

    NullPointerException

    The following code will throw aNullPointerException. Why?

    StringBuilder[] sb1 = new StringBuilder[5];

    sb1[0].append(Hello);

    The StringBuilderobjects in the array have not beeninitialized. To correct the problem:

    for(int i = 0; i

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    12/57

    Checked exceptionsFileNotFoundException is an IOexception. IO

    exceptions are checked exceptions. Mostchecked exceptions come from using I/Oclasses.

    Checked exceptions MUST be handled. Theprogrammer can use a try/catchblock to handlechecked exceptions OR use a throwsstatement in the method declaration to pass

    the treatment up in hierarchy.

    12

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    13/57

    Main exception instructions:

    1. throwthrow (referinta_la_obiect_clsThrowable) ;

    throw new ArithmeticException();

    or,

    Exception oe= new Exception(

    ); throw oe;

    13

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    14/57

    If you throwan exception, your interpreter willstop running the program at that point, whichindicates to the user that they have reached theexception.

    In code you would throw an exception like this:

    throw new Exception(Array index + i + isout of bounds!);

    14

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    15/57

    2. try, catch, finally try{

    declaratii si instructiuni;

    // garde zone...

    }

    catch(clsThrowable ref_oe) {instructiuni;}

    [catch(clsThrowable ref_oe)

    {instructiuni;

    }] [finally{

    instructiuni;

    }]15

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    16/57

    Using a try/catchblock to handle an I/Oexception:

    try{FileReader reader = new FileReader(test.txt);

    }

    catch(IOException e){

    System.out.println(File not found);

    }

    16

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    17/57

    This is an example of handling anIndexOutOfBoundsException with a try/catchblock:

    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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    18/57

    3. throws, to pass up in hierarchy thetreatment tip_val_ret nume_metoda(lista_param) [throws

    tip_clsExceptie] {

    [instructiuni;]

    }

    It is possible to use a throwinstruction in acatch() and the throwswill pass the treatmentup in hierarchy

    18

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    19/57

    Using a throws statement to handle anIOException:

    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 occursthat throws an exception!

    19

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    20/57

    Class exceptions hierarchy

    java.lang.Throwable

    java.lang.Exception java.lang.Error

    java.lang.RuntimeExceptionExcepii specifice Erori

    Exceptii la rulare

    20

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    21/57

    It is possible to have default handler forexceptions managed by the system not bythe programmer

    It is possible to have nested try instructions

    Fromjdk 1.4 we have chainedexceptions, toassociate an exception to other that is

    thrown

    (Ex. The cause of NullPointerExceptionis anArithmeticException)

    21

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    22/57

    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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    23/57

    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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    24/57

    / Sortarea unui sir cu metoda bulelor

    import java.util.*;

    import java.io.DataInputStream;

    import java.lang.String;

    import java.io.IOException;

    class Buble

    {

    ublic 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(

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    25/57

    // Metoda bulelor

    do {

    ok=true;

    for(i=0;iS[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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    26/57

    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 pentru terminare...");

    try{char a=(char) System.in.read();

    }catch(java.io.IOException nume_excep){}}//end main

    }//end class

    26

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    27/57

    *** 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 pentru terminare...atexc1.exc1.main(exc1.java:7)

    27

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    28/57

    User exceptions

    import java.lang.Throwable;

    //clasa proprie pt. tratarea exceptiilor

    class MyException extends Throwable{

    //constructor

    public MyException(){

    //apelul constructorului clasei de baza

    super(Sirulde caractere nu are voie sa fie abc!!!");

    }

    }

    28

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    29/57

    //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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    30/57

    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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    31/57

    import java.lang.Exception;

    class ResultTooLarge extends Exception { ResultTooLarge(String msg)

    {

    super(msg);

    }

    }

    31

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    32/57

    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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    33/57

    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

    bli i id i (S i []){

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    34/57

    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 aface alta actiune"); }

    finally{

    System.out.println("S-a sfarsit aplicatia"); }

    }//main

    } //class Lanseaza

    34

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    35/57

    AssertionsAssertions 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 anegative 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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    36/57

    Assertion Syntax

    There are two different assertion statements:

    assert ; assert : ;

    If the evaluates as false, then

    anAssertionErroris thrown.

    A second argument is optional, but can be declared andwill be converted to a string to serve as a descriptionto theAssertionErrormessage displayed.

    36

    I t l I i t

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    37/57

    Internal Invariants

    Internal invariants are testing values and evaluations inyour methods.

    if (x > 0) {

    // do this

    } else

    {

    assert ( x == 0 );

    // do that

    // what if x is negative?

    }

    37

    C t l Fl I i t

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    38/57

    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

    Cl I i t

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    39/57

    Class InvariantsA 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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    40/57

    Java Collections

    In Java we have classesand interfaces tomanage lists and collections

    A collectionis a group of objects, fromObjectclass (ordered or not).

    It is possible to insert, sort, search, etc.

    It is possible to have different types ofobjects in a collection, or same type

    40

    A ll ti i i t f i th j til

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    41/57

    A collection is an interface in thejava.utilpackage that is used to define a group, or

    collection, of objects.

    It includes sets, lists and map.

    Because it is in thejava.utilpackage, it will

    be necessary to import thejava.utilpackageinto any programs you write using acollection.

    Collections are a very important part of datastoring.

    41

    Collections Without

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    42/57

    Collections Without

    Generics

    Some ground rules for collections:

    The items must be accessible (this typically meansthat the class contains a method that sets the value ofthe 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, anarray 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 containa value for each card and the suit for each card.

    42

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    43/57

    43

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    44/57

    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 eliminatesthe need to use them in the Collections interface class.

    44

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    45/57

    45

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    46/57

    Collection interfaces

    No class offered by Java, but Collectioninterface is inherited by other interfacessuch as: BeanContext, BeanContextServices,

    List, Set and SortedSet.Listinterface control an ordered collection

    of objects. Accepts duplicate objects

    Classes that implement thatinterface:AbstractList, ArrayList,LinkedList, Vector

    46

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    47/57

    47

    public interface Collection {

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    48/57

    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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    49/57

    Setinterface, no duplicate objects

    Classes that implement the interface:

    AbstractSetHashSet

    LinkedHashSet

    TreeSet

    49

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    50/57

    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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    51/57

    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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    52/57

    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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    53/57

    Mapinterface will use an associationKey/Value (Object). The key is unique.

    The association is:-depending on key

    -depending on values

    -depending the association key/value

    53

    bli i t f M {

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    54/57

    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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    55/57

    Classes that implements Mapinterface:

    AbstractMap

    Attributes

    HashMap

    Hashtable

    IdentityHashMap

    RenderingHintsTreeMap

    WeakHashMap

    55

    SortedMap natural or

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    56/57

    SortedMap natural or

    comparator sortpublic 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

  • 8/13/2019 C3 4 Java-Exceptions-Collections 2013

    57/57

    Common Characteristics

    -allows nullelement

    -are serializable

    -clone() method is defined-toString() method is defined

    -allows to create iterators

    -have explicit empty constructors andconstructors with collections asparameters