Sunteți pe pagina 1din 26

1

Prezentare 8:
Exceptii

PROGRAMARE ORIENTATA
OBIECT
2020
Tipuri de erori in Java

Erori sintactice Erori la executie


 Verificabile la compilare  Verificabile la executie
 Utilizare incorecta a  Legate in general de continutul
gramaticii variabilei, nu de tipul ei

 Exemple:  Exemple:
► Lipsa ; ► Variabila null
► Metoda sau variabila ► Downcast incorect
necunoscuta ► Apel incorect de metoda
► Utilizarea unei metode care
nu apartine tipului static al
variabilei
20.11.2020 POO 2
Circumstante exceptionale
/** Rezultat:numarul zecimal reprezentat de s */
int parseInt(String s) { …}
 dar daca s este “un text simpatic”?
/** Rezultat: numarul zecimal reprezentat de s sau -1 daca
* s nu reprezinta un numar zecimal */
 dar daca s este “-1”?
/** Rezultat: numarul zecimal reprezentat de s
* Preconditie: s reprezinta un numar zecimal */
 dar daca s nu respecta uneori preconditia
Trebuie sa tratam cazurile neasteptate

20.11.2020 POO 3
Circumstante exceptionale
/** Rezultat:numarul zecimal reprezentat de s
* Preconditie: s reprezinta un numar zecimal */
int parseInt(String s) { …}
/** Rezultat: “s contine un numar” */
boolean parseableAsInt(String s) { …}

 Ar trebui sa scriem:
if (parseableAsInt(unSir) { In realitate
i = parseInt(unSir); De multe ori scrierea codului
} ignora cazurile de eroare.
else { // trateaza eroarea Trebuie sa existe o cale mai
} simpla.

20.11.2020 POO 4
Circumstante exceptionale

/** Prelucreaza s ca pe un numar zecimal


* Rezultat: numarul zecimal
* Arunca: NumberFormatException daca s nu este un numar */
int parseInt(String s) { …}
 Ce se intampla cand parseInt gaseste o eroare?
► Nu stie ce a determinat eroarea
► Nu poate face nimic cu ea
► “arunca exceptia” metodei apelante
► Executia normala se opreste!

20.11.2020 POO 5
Recuperarea din exceptie

 Blocul try-catch permite tratarea erorilor


► Se executa codul din blocul try-catch
► Daca apare o exceptie, se executa catch
 Exemplu: poate arunca o exceptie NumberFormatException
try {
i = Integer.parseInt(unSir);
tratarea N.F.E.s
System.out.println(“Numarul este: ” + i );
} catch (NumberFormatException nfe)
{System.out.println(“Nu este un numar!”)
}
executat daca apare exceptia

20.11.2020 POO 6
Exceptii in Java
 Exceptiile sunt instante ale clasei Throwable
@105dc  Permite organizarea lor in ierahie
Throwable
“/ cu zero” Throwable probleme care
probleme care nu pot fi
Throwable() Throwable(String) pot fi adresate adresate
getMessage()
Exception Error
Exception
Exception() Exception(String)
RuntimeException
RuntimeException
Runtime…() Run…(String)
ArithmeticException ArithmeticException

Arith…() Arith…(String)
20.11.2020 POO 7
Crearea exceptiilor

public static void f() { int public static void f() {


x = 5 / 0; throw new
Exception(“aruncata”);
} }

Java arunca exceptii Putem arunca exceptii


automat prin throw

20.11.2020 POO 8
De ce exceptii specifice?

public static int f() {  Care este valoarea lui


int x = 0; f()?
try {
A: 0
x = 2;
B: 2
throw new RuntimeException(); C: 3
} catch (RuntimeException e) { D: Nicio valoare. Se opreste!
x = 3; E: Nu stiu
}
return x;
}
20.11.2020 POO 9
De ce exceptii specifice?

public static int f() {  Care este valoarea lui


int x = 0; f()?
try {
A: 0
x = 2;
B: 2
throw new RuntimeException(); C: 3
} catch (Exception e) { D: Nicio valoare. Se opreste!
x = 3; E: Nu stiu
}
return x;
}
20.11.2020 POO 10
De ce exceptii specifice?

public static int f() {  Care este valoarea lui


int x = 0; f()?
try {
A: 0
x = 2;
B: 2
throw new RuntimeException(); C: 3
} catch (ArithmeticException e) { D: Nicio valoare. Se opreste!
x = 3; E: Nu stiu
}
return x; Java utilizeaza tipul
} real al exceptiei
20.11.2020 POO 11
Metode de baza
try {
throw new Exception("Alta Exceptie");
} catch(Exception e) {
System.err.println("Exceptie Prinsa"); Exceptie Prinsa
getMessage():Alta Exceptie
System.err.println("getMessage():" +
getLocalizedMessage():Alta
e.getMessage()); Exceptie
toString():java.lang.Exception: Alta
System.err.println("getLocalizedMessage():" Exceptie
+ e.getLocalizedMessage()); printStackTrace():
java.lang.Exception: Alta Exceptie
System.err.println("toString():" + e); at MetExc.main(MetExc.java:5)
System.err.println("printStackTrace():");
e.printStackTrace();
}

20.11.2020 POO 12
Exceptii si stiva apelurilor

 Apel: 2 . / * * Tratarea exceptiilor* /


Ex.f(); 3. public class Ex {
4. public static void f() {
 Output: 5. g();
ArithmeticException: / cu zero 6. }
7.
la Ex.h(Ex.java:13)
8. public static void g() {
la Ex.g(Ex.java:9)
9. h();
la Ex.f(Ex.java:5) 10 }
11
@3f0b1
12 public static void h() {
ArithmeticException 13 int x = 5/0;
14 }
“/ cu zero”
15 }
20.11.2020 POO 13
Exceptii si stiva apelurilor

 Apel: 2 . / * * Tratarea exceptiilor* /


Ex.f(); 3. public class Ex {
4. public static void f() {
 Output: 5. g();
ArithmeticException: aruncata 6. }
7.
la Ex.h(Ex.java:13)
8. public static void g() {
la Ex.g(Ex.java:9)
9. h();
la Ex.f(Ex.java:5) 10 }
11
@3f0b1
12 public static void h() {
ArithmeticException 13 throw new ArithmeticException (“aruncata”);
14 }
“aruncata”
15 }
20.11.2020 POO 14
Crearea exceptiilor

/ * * O instanta este o exceptie * /


public class OExceptie extends Exception {
Tot ceea ce este necesar
► Nu sunt extra campuri
/ * * Constructor: o instanta cu mesajul m */ ► Nu sunt extra metode
public OExceptie(String m) {
► Doar constructori
super (m);
}

/ * * Constructor: o instanta fara mesaj * /


public OExceptie() {
super();
}

20.11.2020 POO 15
Ierarhia de exceptii

Throwable probleme care nu


probleme pot fi adresate
adresabile

Error
Exception

IOError AssertionError …
FileNotFoundE.
probleme care pot fi
EndOfFileE. RuntimeException prevenite prin
codificare corecta
UnsupportedAudioFileE. …
IndexOutOfBoundsE.
… (toate celelalte)
ArithmeticE. ClassCastE.

exceptii exceptii
“checked" Exceptii “unchecked"
20.11.2020 POO 16
throws si Checked Exceptions

 Apel: 2. /** Tratarea exceptiilor */


Ex.f(); 3. public class Ex {
4. public static void f() throws OExceptie {
 Output: 5. g();
OExceptie: aruncata 6. }
7.
la Ex.h(Ex.java:13)
8. public static void g() throws OExceptie {
la Ex.g(Ex.java:9) 9. h();
la Ex.f(Ex.java:5) 10 }
11
clauza throws este necesara pentru 12 public static void h() throws OExceptie{
ca OExceptie, spre deosebire
13 throw new OExceptie(“aruncata”);
de ArithmeticException, este
“checked exception.” 14 }
15 }
20.11.2020 POO 17
throws si Checked Exceptions
public class Ex {
public static void f() {  throws este necesar:
try {
► Metoda arunca o
g();
exceptie verificabila
} catch (OExceptie ae) {
System.out.println(“prinsa: ” + ae); ► Metoda apeleaza o
} metoda care arunca o
System.out.println(“metoda f()”); exceptie verificabila
}  throws nu este necesar
public static void g() throws OExceptie {
h(); ► Toate exceptiile
} verificabile sunt prinse
public static void h() throws OExceptie { ► Toate exceptiile
throw new OExceptie(“o eroare”); neprinse sunt exceptii
} neverificabile
}
20.11.2020 POO 18
API-ul Java si Exceptii

 API-ul Java documenteaza ce metode arunca


exceptii
► Exemple:
► java.lang.String
 charAt() poate arunca
IndexOutOfBoundsException
 endsWith() poate arunca NullPointerException
► java.lang.Double
 parseDouble() poate arunca
NumberFormatException
 compareTo() poate arunca ClassCastException

20.11.2020 POO 19
Clauza finally

 Necesara cand se doreste restaurarea starii


static int count = 0;
public static void main(String[] args) {
OExceptie
while(true) {
try {
In clauza finally
// count 0 prima data: Nici o exceptie
if(count++ == 0) In clauza finally
throw new OExceptie();
System.out.println("Nici o exceptie");
} catch(OExceptie e) {
System.err.println("OExceptie");
} finally { finally se executa oricum
System.err.println("In clauza finally");
if(count == 2) break; // iesire din while
}
}
20.11.2020 POO 20
Prinderea exceptiilor
 Prinderea unei exceptii nu necesita o potrivire perfecta
// tipul exact:
try {
throw new Exceptie2();
} catch(Exceptie2 s) {
System.out.println("Exceptie2 Prinsa");
} catch(Exceptie1 a) {
Exceptie2 Prinsa
System.out.println("Exceptie1 Prinsa"); Exceptie1 prinsa
}
// tipul de baza:
try {
throw new Exceptie2();
} catch(Exceptie1 a) {
System.out.println("Exceptie1 prinsa");
}

20.11.2020 POO 21
Exceptii - restrictii

 La suprascrierea unei metode nu se pot arunca


decat exceptiile din clasa de baza sau derivate
din ele

DEMO

20.11.2020 POO 22
Conversia exceptiilor

 Daca nu stiu ce sa fac cu o exceptie verificabila

try {
//…
} catch(NuStiuCeSaFacCuExceptiaChecked) {
throw new RuntimeException(e);
}

20.11.2020 POO 23
Exceptii - exemplu
 Vrem sa definim o metoda de calcul a radacinii patratice care
accepta doar o valoare pozitiva ca argument. Metoda arunca o
exceptie daca argumentul este un numar negativ.

class SQRTException extends RuntimeException {


public SQRTException(String mes) {
super(mes);
}

public SQRTException() {
this("SQRT dintr-un numar negativ");
}
}

20.11.2020 POO 24
Exceptii - exemplu

Definim functia de calcul a radacinii patratice in clasa AltaMate.

class AltaMate
{
public static double radPatrat(double val) //throws SQRTException
{
if (val < 0)
throw new SQRTException();
else return Math.sqrt(val);
}
}

20.11.2020 POO 25
Exceptii - exemplu

Un utilizator al clasei AltaMate doreste ca −9 sa fie 3i


class NouaMate {
public static String radPatrat(double val) {
String rez = "";
try {
Double temp = OMate.radPatrat(val);
rez = temp.toString();
}
catch (SQRTException e) {
Double temp = OMate.radPatrat(-val);
rez = temp.toString() + "i";
}
return rez;
}
}
20.11.2020 POO 26

S-ar putea să vă placă și