Title: Exception Handling
1Exception Handling
2Throwing Exceptions with throw
- When an unexpected error condition is
encountered, an exception should be thrown with
throw exception - The exception is represented by an object of
class java.lang.Throwable or a subclass derived
from it - Throwable has a string that can be used to
describe the exception - direct subclasses of Throwable are
- Exception by convention, problems that should
be caught - Error by convention, serious problem that
should not be caught (should cause program
termination)
declares types of exceptions that can be thrown
by this method
public class Conta ... double saldo
... public void levantar(double valor) throws
Exception if (saldo lt valor)
throw new Exception("Saldo insuficiente")
saldo - valor ...
throws an exception, exiting from the method
3Catching Exceptions with try-catch
- To catch and handle exceptions, use a try-catch
block structure - try statements that may throw an exception
(directly or indirectly) catch ( ExceptionType
exceptionReference ) statements to process
an exception - If an exception is thrown when executing the try
block, the try block is interrupted and execution
jumps to the following catch block (assuming
exception of type ExceptionType or a subclass) - We say the exception is caught
- The body of the catch block is the exception
handler - If no exception is thrown, the catch block is not
executed (execution continues after the catch
block)
Conta bancaria conta1 new ContaBancaria()
... try conta1.levantar(100) // método
pode falhar lançando excepção catch
(Exception e) System.err.println("Erro em
conta1.levantar(100) ") ...
4Getting Error Information
- Class Throwable provides, among others, the
following methods - printStackTrace - prints the method call stack
to the standard error stream (System.err) - getMessage - retrieves the error message
- These methods are inherited by all its subclasses
try conta1.levantar(100) catch (Exception
e) System.err.println("Erro em
conta1.levantar(100) " e.getMessage())
e.printStackTrace()
standard error stream
Erro em conta1.levantar(100) Saldo
insuficiente GestaoBancos.ContaBancariaSaldoInsuf
iciente Saldo insuficiente at
GestaoBancos.ContaBancaria.levantar(ContaBancaria.
java107) at GestaoBancos.TesteContas.main
(TesteContas.java64)
5Pass-through Exceptions
try ContaBancaria.transferir(1000.0, conta1,
conta2) catch (Exception e)
System.err.println("Erro a transferir "
e.getMessage())
public static void transferir(double valor,
ContaBancaria origem,
ContaBancaria destino) throws Exception
origem.levantar(valor) destino.depositar(valor
)
public void levantar(double valor) throws
Exception if (saldo lt valor) throw
new Exception("Saldo insuficiente")
saldo - valor
6Advantages of Throwing Exceptions over Returning
Error Codes
- Methods that do not want to handle the errors
need not have any error handling code! - see method transferir in previous slide
- Compare to returning error codes - see below!
- Besides that, if you want to pass more
information about the error you need to return
objects (as we do with exceptions) instead of
error codes
if ( ! ContaBancaria.transferir(1000.0, conta1,
conta2)) System.err.println("Falhou
transferência")
public static bool transferir(double valor,
ContaBancaria origem, ContaBancaria destino)
if ( ! origem.levantar(valor) ) return
false // failure destino.depositar(valor)
return true // success
public bool levantar(double valor) if (saldo
lt valor return false // failure saldo -
valor return true // success
7Uncaught Exceptions
- If an exception is not caught via a try-catch
blocks, program terminates - A message is displayed in the console
- Only exceptions of type Exception (or a subclass
derived from it) can be caught - But catching them is not mandatory, just don't
use try-catch - Exceptions of type Error (or any subclass derived
from it) cannot be caught
8Hierarchy of Exceptions and Errors defined in
java.lang
- Throwable
- Error
- AssertionError
- LinkageError
- ClassCircularityError
- ClassFormatError
- UnsupportedClassVersionError
- ExceptionInInitializerError
- IncompatibleClassChangeError
- AbstractMethodError
- IllegalAccessError
- InstantiationError
- NoSuchFieldError
- NoSuchMethodError
- NoClassDefFoundError
- UnsatisfiedLinkError
- VerifyError
- ThreadDeath
- VirtualMachineError
- Exception (cont.)
- InstantiationException
- InterruptedException
- NoSuchFieldException
- NoSuchMethodException
- RuntimeException
- ArithmeticException
- ArrayStoreException
- ClassCastException
- IllegalArgumentException
- IllegalThreadStateException
- NumberFormatException
- IllegalMonitorStateException
- IllegalStateException
- IndexOutOfBoundsException
- ArrayIndexOutOfBoundsException
- StringIndexOutOfBoundsException
- NegativeArraySizeException
- NullPointerException
extends
9User Defined Exceptions
- Just define a class derived from class Exception
- Advantages
- the name of the class tells the type of exception
- additional fields may be used to store
information about the error - allows selective catching
public class SaldoInsuficiente extends Exception
public SaldoInsuficiente() // contructor
super("Saldo insuficiente") // just calls
superclass constructor
public void levantar(double valor) throws
SaldoInsuficiente if (saldo lt valor)
throw new SaldoInsuficiente() saldo
- valor
try conta1.levantar(100) // método pode
falhar lançando excepção catch
(SaldoInsuficiente e) System.err.println("De
sculpe, mas não tem saldo suficiente")
10Filtering Exceptions
try conta1.levantar(100) // método pode
falhar lançando excepção catch
(SaldoInsuficiente e) System.err.println("De
sculpe, mas não tem saldo suficiente")
Only catches exception of type SaldoInsuficiente
or a subclass derived from SaldoInsuficiente. If
another type of exception is thrown, it is not
caught.
11Multiple catch blocks
public class GestaoBancosException extends
Exception ... public class SaldoInsuficiente
extends GestaoBancosException ... public
class SaldoNegativo extends GestaoBancosException
... void method1() try ...
catch (SaldoInsuficiente e) //
handles exceptions of type SaldoInsuficiente
... catch (GestaoBancosException e)
// handles exceptions of type
GestaoBancosException // and its
subclasses except SaldoInsuficiente ...
catch (Exception e) // handles all
other types exceptions ...
12throws Clause
- Exceptions thrown (and not caught) by a method
must be declared with throwsint methodName(
paramterList ) throws ExceptionType1,
ExceptionType2, // method body - called checked exceptions, because the compiler
checks consistence with the method body - Exceptions of type Error or RunTimeError (or one
of their subclasses) need not be declared - called unchecked exceptions
13Exceptions Thrown in Constructors
- If a constructor detects an error, should throw
an exception - constructor cannot return a value!
- object is destroyed
public class ContaBancaria private double
saldo public ContaBancaria(double saldo)
throws SaldoNegativo if (saldo lt 0)
throw new SaldoNegativo()
this.saldo saldo ...
ContaBancaria conta1 null try conta1 new
ContaBancaria(-1000.0) catch (Exception e)
System.err.println(e.getMessage())
14finally Block
- try-catch, try-catch-finally or try-finally
- finally block always executes upon termination of
the try block - normal termination, at the end of the block
- termination because of break or return statement
- termination because of a caught exception (in
this case, the finally block is executed after
the catch block) or uncaught exception - Usually used to release resources, avoiding
resource leaks
public boolean SearchFor(String file, String
word) throws StreamException Stream input
null try input new Stream(file)
while (!input.eof()) if (input.next()
word) return true return false
finally if (input ! null)
input.close()
15Rethrowing and Wrapping Exceptions
- When a catch block is not able to completely
recovering from the error, may rethrow the same
exception - or may throw a new exception containing the old
exception (as inner exception) for further
information
public static void transferir(double valor,
ContaBancaria origem, ContaBancaria
destino) throws SaldoInsuficiente
destino.depositar(valor) try
origem.levantar(valor) catch(SaldoInsuficien
te e) destino.levantar(valor) throw e
public static void transferir(double valor,
ContaBancaria origem, ContaBancaria
destino) throws TransferirException
destino.depositar(valor) try
origem.levantar(valor) catch(SaldoInsuficien
te e) destino.levantar(valor)
throw new TransferirException(e)
16ExercÃcios
- 12.1 Melhorar as classes de gestão de contas
bancárias com tratamento de erros apropriado.