Java Exceptions

Exceptions can be used to jump out of the current code block, specifying a type of error, which can then be properly dealt with in the code outside of the block.

Throwing exceptions

public void myFunction () throws Exception { // Your code here if ( /* Your condition here */ ) { throw new Exception ("Your error text"); } }
  • To be more specific, you can replace Exception with other kinds of exceptions such as IllegalArgumentException, NumberFormatException, etc.

Try-catch blocks

public void myFunction () { try { // Code that might fail (throw exceptions) } catch (Exception myException) { // Code to respond if it fails } }
  • Use this when calling functions that may throw an exception.

Throwing and catching different kinds of exceptions

public void myFunction () { try { // Code that might fail (throw exceptions) } catch (IllegalArgumentException myIAException) { // Code to respond if it fails } catch (Exception myException) { // Code to respond if it fails } }
  • Use this to react differently to different errors.
  • If you catch a general Exception, put that after the more specific Exception catches or they can't be reached.

Stack Trace

catch (Exception myException) { myException.printStackTrace(); }
  • Use this to have the program display (in the console) the line of the error, and sequence of calls that lead to it.

Challenge

Write a function that will throw an IllegalArgumentException if the parameters are in the wrong format. Call that function and have it display a error if it fails. Run the code with invalid parameters to test it.

Quiz

Completed