Throws keyword in java is used to declare exceptions that can be thrown by the method. Throws keyword can be used to throw multiple exception.
syntax:
1. Throws single exception
1 |
methodName(methodParams ..) throws exceptionNames |
example:
1 |
public readFile(String fileName) throws IOException |
2. Throws multiple exception
1 |
methodName(methodParams ..) throws exceptionName1,exceptionName2,... |
example:
1 |
public readFile(String fileName) throws IOException,FileNotFoundException |
When a method throws an exception, the code that uses this method needs to handle this exception.
Handling of exception can be of 2 types
1. Use a Try-Catch block
2. Use throws method to again throw the same or new exception.
Lets see an example where we have a method convertListToString that throws exception.
In main method we call the convertListToString and also handle the exception that was thrown.
Example : Throws in exception handling
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
package com.kscodes.sampleproject; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ExecptionHandling { public static void main(String[] args) { List<String> arrList1 = new ArrayList<>(Arrays.asList("Java", "JSP", "JavaScript", "JQuery")); try { System.out.println("Converting ArrayList 1"); String convertedList = convertListToString(arrList1); System.out.println(convertedList); } catch (IOException e) { System.out .println("Exception while converting ArrayList 1. Exception Message is " + e.getMessage()); } System.out.println("**********************************************"); List<String> arrList2 = null; try { System.out.println("Converting ArrayList 2 which was null"); String convertedList = convertListToString(arrList2); System.out.println(convertedList); } catch (IOException e) { System.out.println("Exception while converting ArrayList 2."); e.printStackTrace(); } } public static String convertListToString(List<String> list) throws IOException { /* * Check if list is null and then throw IOException */ if (list == null) { throw new IOException(); } String convertedString = ""; for (String str : list) { convertedString = convertedString + str; } return convertedString; } } |
Output
1 2 3 4 5 6 7 8 |
Converting ArrayList 1 JavaJSPJavaScriptJQuery ********************************************** Converting ArrayList 2 which was null Exception while converting ArrayList 2. java.io.IOException at com.kscodes.sampleproject.ExecptionHandling.convertListToString(ExecptionHandling.java:44) at com.kscodes.sampleproject.ExecptionHandling.main(ExecptionHandling.java:29) |