There are many different concepts to learn when learning a programming language. Many of these concepts are like grammar in spoken languages – they help keep it structured and functioning properly. Handling exceptions in Java is an important skill in becoming a good Java programmer.
Exceptions are thrown when the program has encountered an error. Once the exception is thrown, it is up to the programmer to decide what happens next. The most common and the worst handling of an exception is silently ignoring it. Printing stack trace to the console should at least be done so that pinpointing an error is easier.
EditChecked vs Unchecked Exceptions
Checked exceptions are classes derived from Exception class and are thrown when the program can recover from the exception and they must either be caught using one of the try blocks or rethrown. Unchecked exceptions are classes derived from RuntimeException and are thrown when the program cannot recover from the exception and they don't have to be caught or rethrown. Generally, unchecked exceptions are a result of a programming error and can be avoided (e.g. checking if a variable is null to prevent NullPointerException).
Since unchecked exceptions produce cleaner code, programmers favor it over checked exceptions and nowadays it basically comes down to a personal choice. However, exceptions in the Java API abide the difference.
| Checked | Unchecked |
|---|---|
| IOException | NullPointerException |
| ClassNotFoundException | IllegalArgumentException |
| InterruptedException | IllegalStateException |
EditSteps
EditUsing Try-Catch-Finally
-
Create a class and the main method. Create a class and name it however you want and inside the class create the main method.
public class HandleExceptionExample { public static void main(String[] args) { } }
-
Declare three primitive integer variables and perform division. Declare three
int(primitive integer) variables and name themdividend,divisorandquotient. Assign an arbitrary number todividendvariable, assign zero todivisorvariable and assign quotient ofdividendanddivisortoquotientvariable. Printquotientvariable to the console.public class HandleExceptionExample { public static void main(String[] args) { int dividend = 50; int divisor = 0; int quotient = dividend / divisor; System.out.println(quotient); } }
-
Compile and run the program. Program prints exception stack trace to the console and terminates the execution at the line where the
quotientvariable is assigned a value.Quotientvariable will never be printed to the console because uncaught exceptions, on the line they were thrown, break out of the method. -
Catch and handle exception. Assign a number zero to the
quotientvariable and create try-catch block withArithmeticExceptionin thecatchstatement. Inside thetryblock, dividedividendanddivisorvariables and assign their quotient to thequotientvariable. Inside thecatchblock, print the exception stack trace to the console. After the try-catch block, print thequotientvariable to the console.public class HandleExceptionExample { public static void main(String[] args) { int dividend = 50; int divisor = 0; int quotient = 0; try { quotient = dividend / divisor; } catch (ArithmeticException e) { e.printStackTrace(); } System.out.println(quotient); } }
-
Compile and run the program. Program prints exception stack trace to the console, but does not terminate the execution at the line where the
quotientvariable is assigned a value.Quotientvariable is also printed to the console, but before the exception. -
Add
finallyblock.finallyblocks are always executed after thetryand/orcatchblocks and they are mostly used to release the resources. Instead of after the try-catch-finally block, print thequotientvariable to the console inside thefinallyblock.public class HandleExceptionExample { public static void main(String[] args) { int dividend = 50; int divisor = 0; int quotient = 0; try { quotient = dividend / divisor; } catch (ArithmeticException e) { e.printStackTrace(); } finally { System.out.println(quotient); } } }
-
Compile and run the program. Program prints exception stack trace, and
quotientvariable right after, to the console.
EditUsing Try-With-Resources
-
Create a class and the main method. Create a class and name it however you want and inside the class create the main method.
public class HandleExceptionExample { public static void main(String[] args) { } }
-
Create try-catch block. Create try-catch block and add parenthesis to the
trystatement.public class HandleExceptionExample { public static void main(String[] args) { try () { } catch () { } } }
-
Add resource to the
tryand exception to thecatchstatement. InstantiateFileReaderandFileas its parameter in thetrystatement. In thecatchstatement, addIOExceptionand inside the block, print stack trace to the console.public class HandleExceptionExample { public static void main(String[] args) { try (FileReader reader = new FileReader(new File("filename"))) { // code omitted } catch (IOException e) { e.printStackTrace(); } } }
-
Finished. Using try-with-resources automatically releases the resources back to the operating system. Think of it as an automatic
finallyblock. If exception is thrown while reading the file,reader.close()will be automatically called.- The equivalent using try-catch-finally:
FileReader reader = null; try { reader = new FileReader(new File("filename")); // code omitted } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } }
- The equivalent using try-catch-finally:
EditVideo
EditTips
- If you're unsure of what exception to catch, you can always catch the superclass for all exceptions, the
Exceptionclass. - Catching and handling more than one exception is possible. There are multiple ways to do so:
- To catch and handle multiple exceptions separately, add another catch statement and block at the end of the try-catch block.
try { Socket socket = new Socket("localhost", 5940); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
UnknownHostExceptionwill only be caught if it is located before theIOExceptionsince the former is derived from the latter. Otherwise it will be caught withIOException. If there is no need to go into detail with exceptions, only the superclass needs to be caught.try { Socket socket = new Socket("localhost", 5940); } catch (IOException e) { e.printStackTrace(); }
- To catch and handle multiple exceptions together, add multiple exceptions in the same catch statement separated by the
|character. However, those exceptions must have different superclasses. For example,UnknownHostExceptionandIOExceptioncannot be caught like this because the latter is a superclass of the former.try { Socket socket = new Socket("localhost", 5940); } catch (IllegalArgumentException | IOException e) { e.printStackTrace(); }
- To catch and handle multiple exceptions separately, add another catch statement and block at the end of the try-catch block.
EditWarning
- Silently ignoring is a bad practice and the worst method of exception handling. Example of silently ignoring an exception:
try { // code omitted } catch (Exception e) { }
EditRelated wikiHows
source How to of the Day http://ift.tt/2cWEGpt
Aucun commentaire:
Enregistrer un commentaire