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
Now Reading
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
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
Any beginner will face problems when they start their Java programming journey. The problems thrown are usually errors or exceptions in Java. It is imperative to have basic knowledge about error vs. exception in Java.
In this tutorial, we will learn how to manage errors vs. exceptions in Java.
Errors are special circumstances that normally cannot be repaired and denote major issues prohibiting the program from running properly in Java. Errors are frequently brought on by outside variables or serious internal problems with the Java Virtual Machine (JVM). Here are a few typical Java errors:
It's crucial to keep in mind that errors often aren't intended to be detected and addressed by the application code because they typically point to serious issues. Instead, the JVM or underlying system is designed to detect and manage faults to ensure the program's stability.
This error occurs when the call stack used to track method calls exceeds its limit due to infinite recursion.
public class upGradTutorials {
public static void recursiveMethod() {
recursiveMethod();
}
public static void main(String[] args) {
recursiveMethod();
}
}
This error occurs when the Java Virtual Machine (JVM) cannot allocate more memory for an object because the heap space is exhausted.
public class upGradTutorials {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
while (true) {
numbers.add(1);
}
}
}
(output in local development environment)
The NoClassDefFoundError is a runtime error that occurs when the JVM cannot find a class that was present during compilation.
public class upGradTutorials {
public static void main(String[] args) {
NonExistentClass obj = new NonExistentClass();
}
}
(output in local development environment)
This error occurs when the JVM cannot find a referenced method at runtime.
public class upGradTutorials {
public static void main(String[] args) {
String str = "upGrad teaches Java.";
int length = str.getLength(); //
System.out.println(length);
}
}
(output in local development environment)
This error occurs when a subclass fails to provide an implementation for an abstract method declared in its superclass or interface.
(upGradTutorials.java file)
public class upGradTutorials extends AbstractClass {
public static void main(String[] args) {
upGradTutorials obj = new upGradTutorials();
obj.abstractMethod();
}
}
(AbstractClass.java file)
public abstract class AbstractClass {
public abstract void abstractMethod();
}
(output in local development environment)
Exceptions are objects that indicate extraordinary circumstances that arise while a programme is being executed in Java. These circumstances alter the program's typical flow and can call for special intervention. Exceptions offer a way to deal with and move past these extraordinary circumstances.
Checked exceptions and unchecked exceptions are the two categories into which exceptions in Java are split.
The Java runtime creates an exception object when an unusual condition occurs, which stores details about the error, including the kind of exception, a description, and the status of the program at the time. The program then passes control to a particular section of code known as an exception handler after throwing the exception object.
public class upGradTutorials {
public static void main(String[] args) {
try {
Class.forName("com.example.NonExistentClass");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
In this example, we try to load a class com.example.NonExistentClass using Class.forName(). However, since the class doesn't exist, the compiler will detect this during compilation and raise a ClassNotFoundException. The catch block is included to handle the exception and print the stack trace.
public class upGradTutorials {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
int value = numbers[3];
}
}
In this example, we attempt to access the element at index 3 in the array numbers. However, since the valid indices for this array are 0, 1, and 2, the compiler will detect this out-of-bounds access during compilation and raise an ArrayIndexOutOfBoundsException.
public class upGradTutorials {
public static void main(String[] args) {
String str = null;
int length = str.length();
System.out.println(length);
}
}
In this example, we initialize the variable str with null. Then, we try to call the length() method on str, which results in a NullPointerException because we are invoking a method on a null reference.
public class upGradTutorials {
public static void main(String[] args) {
int result = divide(10, 0); // Dividing by zero
System.out.println(result);
}
public static int divide(int a, int b) {
return a / b;
}
}
In this example, we have a method divide that takes two integers and performs division. We attempt to divide 10 by 0, which is not allowed and leads to an ArithmeticException.
In the above code, we have the recursiveMethod that calls itself recursively without any base case to stop the recursion. As a result, the method keeps calling itself indefinitely, eventually causing a StackOverflowError when the call stack exceeds its limit.
Running this code will throw a StackOverflowError and terminate the program abruptly without any handling or recovery. It's important to handle or prevent StackOverflowError when writing production code to ensure the stability and reliability of your application.
Now, let us handle this error:
To handle the StackOverflowError, we use a try-catch block in the main method. We catch the StackOverflowError and print a message indicating the error was caught. Inside the catch block, you can handle any necessary error or take appropriate action based on your application's requirements.
Code:
public class upGradTutorials {
public static void main(String[] args) {
try {
recursiveMethod(0);
} catch (StackOverflowError e) {
System.out.println("Caught StackOverflowError: " + e.getMessage());
// Handle the exception or take appropriate action
}
}
public static void recursiveMethod(int i) {
System.out.println("Iteration: " + i);
recursiveMethod(i + 1); // Recursive call
}
}
In the above code, we use the Class.forName() method to attempt to load a class that does not exist (com.example.NonExistentClass). Since the class does not exist, it will throw a ClassNotFoundException. When this exception is thrown and not handled, the program will terminate abruptly and display an error message indicating the class was not found.
Now, let us handle this exception:
In this code, we use the Class.forName() method to attempt to load a class that does not exist (com.example.NonExistentClass). Since the class does not exist, it will throw a ClassNotFoundException.
To handle this exception, we surround the Class.forName() statement with a try-catch block. If the class is not found, the catch block is executed. In this example, we simply print a message indicating that the class was not found, but you can customize the handling logic based on your requirements.
Handling the ClassNotFoundException allows your program to gracefully handle the situation when a required class is missing and provides an opportunity to handle the exception or take appropriate action, such as logging an error, displaying a user-friendly message, or providing an alternative behavior.
Code:
public class upGradTutorials {
public static void main(String[] args) {
try {
// Attempt to load a class that does not exist
Class<?> cls = Class.forName("com.example.NonExistentClass");
System.out.println("Class loaded: " + cls.getName());
} catch (ClassNotFoundException e) {
System.out.println("Class not found: " + e.getMessage());
// Handle the exception or take appropriate action
}
}
}
Errors and exceptions are distinct concepts in the Java programming language. The key difference in errors and exceptions in Java is as follows:
Properties | Error | Exception |
Causes | Errors result from major issues that are normally out of the application's control and frequently point to fundamental flaws with the JVM or the underlying system. OutOfMemoryError and StackOverflowError are two examples of errors. | On the other hand, exceptions are brought on by extraordinary circumstances that arise throughout the course of the program's execution and can be handled and overcome. They stand for unforeseen events or runtime faults the programmer can foresee and fix. |
Recovery | Errors typically cannot be fixed quickly because they signify serious issues that frequently result in program cancellation. | On the other side, exceptions offer a method for handling errors and recovering from them. You can gracefully handle uncommon circumstances, present error messages or alternate behaviors, and continue program execution by capturing and handling exceptions. |
Types | Errors are always unchecked. | Exceptions can be checked and unchecked. |
Package | It belongs to java.lang.Error package. | It belongs to java.lang.Exception package. |
Errors are serious issues that frequently point to faults with the JVM or the underlying system and are not meant to be detected and managed by application code. On the other hand, exceptions are used to manage extraordinary circumstances that arise during the execution of the program and offer a means of recovering from them. While the JVM or system often handles mistakes, exceptions can be caught and regulated by the programmer using try-catch blocks or propagated up the call stack.
Checking out a specially curated course from upGrad can help you get a better understanding of various Java concepts.
1. What is exception propagation in Java?
In Java, the process by which an exception thrown in one method can be forwarded up the call stack to be captured and handled by the proper exception handler in a higher-level function is known as exception propagation.
2. How do you handle checked exceptions?
In Java, there are two ways to handle checked exceptions: either you can catch the exception using a try-catch block, or you may declare the exception to be thrown by using the “throws” keyword in the method signature.
3. What happens when an exception is thrown by the main method?
The default Java exception handling mechanism is used when an exception is thrown by the main method. The behavior, however, relies on whether the exception is a checked exception or an unchecked exception if it is not captured and handled within the main function itself.
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...