Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
Now Reading
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Error handling is a key concept every programmer should master before creating deployable applications. No matter how sophisticated the code is, every program will throw errors during compilation or runtime.
It is prudent to know how to handle these errors, and the most common way to handle them is by handling the exceptions that the code might raise. Exception handling doesn’t only pertain to Java but almost every programming language that exists.
In this read, we’re going to delve into the difference between throw and throws in Java, we’re going to look into the code for both and how to implement both of these keywords into programs. Read on to learn how to implement the throw and throws clause in your code.
The throw and throws keyword in Java is used to handle exceptions you know your code might raise. For example, if you create a program that takes a number from the user and then divides it by another number given by the user, there is a chance that the user might enter ‘0’ as the divisor.
If you do not have this exception handled, your program will throw an error and not provide you with the desired output. So you can handle the exception by providing a customized message saying, “The divisor cannot be zero”.
The above is a small example of how exceptions are handled using the throw clause. However, in production-ready applications, exception handling is used extensively.
There are a few key differences between throw and throws in Java mentioned in the table below:
Throw | Throws |
The "throw" exception in Java is used within the body of a method to throw an exception explicitly. | The "throws" keyword is used in the method signature to declare the potential exceptions that a method may throw. |
It allows programmers to create their own exceptions or throw predefined exceptions to handle specific scenarios. | It informs the caller of the method and possible exceptions that need to be handled or propagated. |
It is used when a specific condition or error occurs within the method that requires an exception to be thrown. | It does not throw exceptions; it is a declaration mechanism. |
It transfers the control to the caller, indicating an exceptional condition. | It allows the caller to handle the declared exceptions or pass them on to higher-level methods. |
As we now know the key differences, let’s delve into the coding segment to understand the difference between throw and throws with example in Java. We’ll get into the throw clause and how to handle exceptions using Java:
Arithmetic Exception using throw clause:
public class Throw {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static int divide(int dividend, int divisor) {
if (divisor == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return dividend / divisor;
}
}
In the example above, we have a function called ‘divide’ that takes two integers in as arguments and performs division.
The parameters passed while invoking the function ‘divide’, are ‘10’ and ‘0’, ‘0’ being the divisor. The function throws an ArithmeticException with a custom error message saying that the dividend cannot be divided by the divisor ‘0’.
In the main method, we’re invoking the divide method within a try-catch block to handle the exception. If an exception is thrown in the try block, the catch block is executed, and the error message is printed.
e.getMessage() is a method that is used to retrieve the error message associated with an exception object e. You can rename ‘e’ to what you desire, but you have to change it according to the occurrences of the code.
The getMessage() method is an in-built method provided by Java that lets you access the error message as a string.
Try changing the value of the divisor to ‘1’ in the ‘try’ block in the above program to see the results.
Replace int result = divide(10, 0); with int result = divide(10, 1);
Below are a few more examples of how you can use the ‘throw’ clause for more exceptions:
public class Throw{
public static void main(String[] args) {
try {
String text = null;
if (text == null) {
throw new NullPointerException("Text is null");
}
} catch (NullPointerException e) {
System.out.println("NullPointerException occurred: " + e.getMessage());
}
}
}
To handle the NullPointerException using the “throw” clause, we’re declaring a String called “text” and set its value to null inside the try block. Note that we’re explicitly trying to create the NullPointerException in the code above.
We use a conditional statement after that to check whether the String “text” value is null or not. If it is null, then we “throw” a NullPointerException saying that the “Text is null”, catch the same exception in the catch block, and display a custom message addressing the NullPointerException.
public class Throw{
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
int index = 3;
if (index < 0 || index >= numbers.length) {
throw new ArrayIndexOutOfBoundsException("Invalid index: " + index);
}
int value = numbers[index];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException occurred: " + e.getMessage());
}
}
}
In the code above, we’re explicitly trying to raise the ArrayIndexOutOfBoundsException. When you try to access an array backed with a non-existent index, you get an ArrayIndexOutOfBoundsException. This exception signifies that the index you’re trying to access is either less than 0 or more than or equal to the array's length.
In the ‘try’ block, we take an array of the integer data type called ‘numbers’ and add the elements 1, 2, and 3 in it. So the accessible indexes are 0, 1, and 2. Next, we take an integer called index and assign the value of 3 to it.
We use the “if” statement to check whether the index is less than ‘0’ or greater than the length of the array, i.e., 3. In case the “if” statement returns a “TRUE” value, we use the “throw” clause to raise an ArrayIndexOutOfBoundsException, handle it in the catch block, and print a customized message.
The "throws" keyword is used in the method signature to declare the potential exceptions that a method may throw. Keep reading if you’re wondering in which situation the throws clause is used.
Let’s take the same example of an ArithmeticException used in the example above and implement the same using the “throws” keyword.
public class Throws {
public static void main(String[] args) {
Throws calculate = new Throws();
int dividend = 10;
int divisor = 0;
try {
int result = calculate.divide(dividend, divisor);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
public int divide(int dividend, int divisor) throws ArithmeticException {
if (divisor == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return dividend / divisor;
}
}
In the example above, we declare the divide method to throw an ArithmeticException using the “throws” keyword. Any code calling this method must handle or declare this exception.
We check if the divisor is ”0” within the method divide. If it is “0”, we throw a new ArithmeticException with a specific error message using the throw keyword.
In the main method, we create an instance of the class “Throws” and call the divide method. We put the function ‘divide’ on the object ‘calculate’ in a try-catch block to catch any ArithmeticException that may be thrown. If the exception occurs, i.e., when the divisor is ‘0’, we print an error message.
Using the ‘throws’ keyword, we inform callers that the divide method may throw an ArithmeticException if an invalid division operation occurs.
The advantage of using “throws ArithmeticException” is that anyone trying to use the function “divide” will have to handle or declare the exception in their main() method. This makes the function reusable within any class and reduces the chances of errors.
Exception handling is a key concept to learn if you are trying to code in Java. Instead of letting the program throw you unexpected errors, it is much wiser to put your code in the try-, catch- and finally-block in Java and handle those errors using the throw and throws clause.
Developers use both clauses in their code extensively as it helps them deal with potential problems that might arise during the runtime of their application. It also helps with the entire debugging and troubleshooting process, providing a mechanism to locate and diagnose the problems within their code.
1. What is the finally keyword in Java?
The finally keyword in Java is used to run a segment of code under the ‘finally’ block. This code segment will execute regardless of whether an exception occurs.
2. Is there a difference between throw and throws in C#?
The ‘throws’ clause does not exist in C#. Exceptions in C# are handled using the ‘throw’ keyword.
3. What is throwable in Java?
"Throwable" refers to a class hierarchy representing exceptions and errors. All exceptions and errors commence in the Throwable class.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...