Java Exceptions – Try..Catch
Java Exceptions
While executing Java code, we may get different errors such as coding errors made by the programmer, errors due to wrong input or other unpredictable errors.
When an error occurs, Java will normally stop and generate an error message, which is technically called as exception. Hence, when there is an error in the code, Java will throw an Exception.
Java Try and Catch
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in a try block.
The try and catch keywords usually come in pairs.
Syntax
try { // Block of code to try for errors } catch (Exception e) { // Block of code to be executed when error has encountered in try }
Example
The following code will throw an Exception : ArrayIndexOutofBoundException:
String colors[]={"red", "orange", "pink", "brown"}; System.out.println(colors[4]);
Exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at practices.Loops.main(Loops.java:8)
To avoid the above situation, we use try…catch block in the code. For example
Example
String colors[]={"red", "orange", "pink", "brown"}; try { System.out.println(colors[4]); } catch (Exception e) { System.out.println("Something went wrong"); }
Output
Something went wrong
Finally
The finally statement will execute code, after try…catch, regardless of the result.
Syntax
try { // Block of code to try for errors } catch (Exception e) { // Block of code to be executed when error has encountered in try } finally { // Block of code will be executed after try…catch block }
Example
String colors[]={"red", "orange", "pink", "brown"}; try { System.out.println(colors[4]); } catch (Exception e) { System.out.println("Something went wrong"); } finally { System.out.println("The 'try catch' is finished"); }
Output
Something went wrong The 'try catch' is finished
The throw keyword
The throw statement allows you to create a custom error. The throw statement is used together with many Exception types such as ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundException, SecurityException, etc.
Example
In the below example, if the age is less than 18 then it throws an error.
public class ExcpetionExample { static void checkAge(int age){ if (age < 18){ throw new ArithmeticException ("Access Denied - Should be minimum of age 18"); } else { System.out.println("Access granted"); } } public static void main (String args[]){ checkAge(16); } }
Output
Exception in thread "main" java.lang.ArithmeticException: Access Denied - Should be minimun of age 18
at practices.ExcpetionExample.checkAge(ExcpetionExample.java:6)
at practices.ExcpetionExample.main(ExcpetionExample.java:12)
It the age is above 18, it prints the String “Access granted”
Example
checkAge(20);
Output
Access granted