Try and Catch Statements

Submitted by: 

This page will teach you about the Try and Catch statements in Java.

What is a Try and Catch statement?
A Try and Catch statement is a very handy statement which allows the program to handle errors and warnings thrown by the scripts. Each Try and Catch statement contains the block of script to handle, a single or multiple exception(s) followed by block(s) of script which are executed if that specific exception is thrown by the handled script. The 'final' block always comes last and is executed whenever any exception is thrown.

When are Try and Catch statements used?
Try and Catch statements are used in complex scripts that can be un-predictable or not easily handled by user scripts created within the program.


  1. try {
  2. String nothing = "";
  3. nothing = nothing.substring(0, 8);
  4. } catch (Exception e) {
  5. System.out.println("Exception: " + e.toString());
  6. }

The above code tries to get a substring from the index of 0 to the index of 8 within the main string "nothing". The problem with our code is that "nothing" has no value of the index of 8 is invalid, which is shown through the output that is given in our console from the exception:

Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 8


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.