O Programador pode definir novos tipos de exceções, criando subclasses da classe Exception
class MinhaExcecao extends Exception { }
class MinhaClasse { void oops() throws MinhaExcecao { if (/* não ocorreu erro */) { ... } else { /* ocorreu erro */ throw new MinhaExcecao(); } } }
Class MeuTestadordeExcecao { public static void main(String args[]) { MinhaClasse teste = new MinhaClasse(); try { test.oops(); } catch (NullPointerException e) { System.out.println("teste era igual a null"); } catch (MinhaExcecao e) { System.out.println("Esta é MinhaExcecao !"); } catch (Exception e) {
System.out.println("Outro erro ocorreu"); } catch (Object obj) { System.out.println("Um outro objeto foi levantado - REVER ISTO !"); } } }
try { f.open(); } catch (Exception e) { f.close(); throw e; }
try { // faz algo } finally { // limpa tudo ao sair }é similar ao código abaixo
try { // faz algo } catch (Object obj) { //limpa tudo ao sair throw obj; } // limpa tudo ao sairoutro trecho de código com uso de finally
try { if (a == 10) { return; } } finally { System.out.println("Entrei no finally"); } System.out.println("a variável \"a\" nao é igual a 10.");