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
,divisor
andquotient
. Assign an arbitrary number todividend
variable, assign zero todivisor
variable and assign quotient ofdividend
anddivisor
toquotient
variable. Printquotient
variable 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
quotient
variable is assigned a value.Quotient
variable 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
quotient
variable and create try-catch block withArithmeticException
in thecatch
statement. Inside thetry
block, dividedividend
anddivisor
variables and assign their quotient to thequotient
variable. Inside thecatch
block, print the exception stack trace to the console. After the try-catch block, print thequotient
variable 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
quotient
variable is assigned a value.Quotient
variable is also printed to the console, but before the exception. -
Add
finally
block.finally
blocks are always executed after thetry
and/orcatch
blocks and they are mostly used to release the resources. Instead of after the try-catch-finally block, print thequotient
variable to the console inside thefinally
block.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
quotient
variable 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
try
statement.public class HandleExceptionExample { public static void main(String[] args) { try () { } catch () { } } }
-
Add resource to the
try
and exception to thecatch
statement. InstantiateFileReader
andFile
as its parameter in thetry
statement. In thecatch
statement, addIOException
and 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
finally
block. 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
Exception
class. - 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(); }
UnknownHostException
will only be caught if it is located before theIOException
since 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,UnknownHostException
andIOException
cannot 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) { }
No comments:
Post a Comment