Qual é a diferença entre arremesso vs. joga em Java
Publicados: 2013-07-23Um declara e o outro faz
Existem cinco palavras-chave relacionadas ao tratamento de exceções em Java, por exemplo , try, catch, finally, throw e throws . Além da diferença entre final, finally e finalize , throw vs throws é uma das perguntas mais frequentes da entrevista em Java.
- A palavra- chave throw é usada para lançar Exception de qualquer método ou bloco estático em Java enquanto throws keyword , usado na declaração do método, denota qual Exception pode ser lançada por este método. Eles não são intercambiáveis.
- Se algum método lançar uma exceção verificada conforme mostrado no exemplo abaixo, o chamador poderá manipular essa exceção capturando-a ou poderá lançá-la novamente declarando outra cláusula throws na declaração do método.
- A cláusula Throw pode ser usada em qualquer parte do código em que você sente que uma exceção específica precisa ser lançada para o método de chamada.
Subestimando exceções Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
java . lang . Object | +-- java . lang . Throwable | +-- java . lang . Exception | | | +-- java . lang . ClassNotFoundException | | | +-- java . io . IOException | | | | | +-- java . io . FileNotFoundException | | | +-- java . lang . RuntimeException | | | +-- java . lang . NullPointerException | | | +-- java . lang . IndexOutOfBoundsException | | | +-- java . lang . ArrayIndexOutOfBoundsException | +-- java . lang . Error | +-- java . lang . VirtualMachineError | +-- java . lang . OutOfMemoryError |
Se um método estiver lançando uma exceção, ele deve ser cercado por um bloco try catch para capturá-lo ou esse método deve ter a cláusula throws em sua assinatura. Sem a cláusula throws na assinatura, o compilador Java JVM não sabe o que fazer com a exceção. A cláusula throws informa ao compilador que essa exceção específica seria tratada pelo método de chamada.
Abaixo está um exemplo muito simples que explica o comportamento do bloco Throw, Throws, Try, Catch, Finalmente em Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
package com . crunchify . tutorials ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; /** * @author Crunchify.com */ public class CrunchifyThrowThrows { @SuppressWarnings ( "unused" ) public static void main ( String args [ ] ) throws Exception { FileInputStream crunchifyStream1 = null ; FileInputStream crunchifyStream2 = null ; String fileName = "Crunchify.txt" ; System . out . println ( "main: Starting " + CrunchifyThrowThrows . class . getName ( ) + " with file name = " + fileName ) ; // get file input stream 1 try { crunchifyStream1 = crunchifyTest1 ( fileName ) ; } catch ( FileNotFoundException ex ) { System . out . println ( "main: Oops, FileNotFoundException caught" ) ; } catch ( Exception ex ) { System . out . println ( "main: Oops, genreal exception caught" ) ; } // get file input stream 2 crunchifyStream2 = crunchifyTest2 ( fileName ) ; System . out . println ( "main: " + CrunchifyThrowThrows . class . getName ( ) + " ended" ) ; } public static FileInputStream crunchifyTest1 ( String fileName ) throws FileNotFoundException { FileInputStream crunchifyStream = new FileInputStream ( fileName ) ; System . out . println ( "crunchifyTest1: File input stream created" ) ; return crunchifyStream ; } public static FileInputStream crunchifyTest2 ( String fileName ) throws Exception { FileInputStream crunchifyStream = null ; try { crunchifyStream = new FileInputStream ( fileName ) ; } catch ( FileNotFoundException ex ) { throw new Exception ( "crunchifyTest2: Oops, FileNotFoundException caught" ) ; //System.out.println("crunchifyTest2: Oops, FileNotFoundException caught"); } finally { System . out . println ( "crunchifyTest2: finally block" ) ; } System . out . println ( "crunchifyTest2: Returning from crunchifyTest2" ) ; return crunchifyStream ; } } |
Resultado:

1 2 3 4 5 6 |
main : Starting com . crunchify . tutorials . CrunchifyThrowThrows with file name = Crunchify . txt main : Oops , FileNotFoundException caught crunchifyTest2 : finally block Exception in thread "main" java . lang . Exception : crunchifyTest2 : Oops , FileNotFoundException caught at com . crunchify . tutorials . CrunchifyThrowThrows . crunchifyTest2 ( CrunchifyThrowThrows . java : 45 ) at com . crunchify . tutorials . CrunchifyThrowThrows . main ( CrunchifyThrowThrows . java : 30 ) |
Agora basta substituir as linhas 45 e 46 pela linha abaixo para ver o resultado abaixo:
1 2 |
//throw new Exception("crunchifyTest2: Oops, FileNotFoundException caught"); System . out . println ( "crunchifyTest2: Oops, FileNotFoundException caught" ) ; |
Novo resultado:
1 2 3 4 5 6 |
main : Starting com . crunchify . tutorials . CrunchifyThrowThrows with file name = Crunchify . txt main : Oops , FileNotFoundException caught crunchifyTest2 : Oops , FileNotFoundException caught crunchifyTest2 : finally block crunchifyTest2 : Returning from crunchifyTest2 main : com . crunchify . tutorials . CrunchifyThrowThrows ended |
Lista de todos os tutoriais de Java nos quais você pode estar interessado.
Dicas de bônus sobre exceções:
- A execução normal do programa é imediatamente ramificada quando uma exceção é lançada.
- As exceções verificadas devem ser capturadas ou encaminhadas. Isso pode ser feito em uma instrução try … catch ou definindo a exceção na definição do método.
- A exceção é capturada pelo primeiro bloco catch cuja classe de exceção associada corresponde à classe ou superclasse da exceção lançada.
- Se nenhum bloco catch correspondente for encontrado na cadeia de exceção, o encadeamento que contém a exceção lançada será encerrado.
- O bloco finally após uma instrução try … catch é executado independentemente de uma exceção ser capturada ou não.
- Retornar dentro de um bloco finally quebra a cadeia de exceção para o invocador, mesmo para exceções não capturadas.