In the typical project life cycle, around 20% of the total duration is devoted to the development phase and the initial release, with the remaining 80% being the maintenance phase. It's essential to recognize that if the product lacks a robust architecture, there is an increased likelihood that the code will become more error-prone as new features are introduced over time. Regardless of the circumstances, one universal truth remains: bugs are an integral part of the product life cycle.
Still there are some bugs that creep into the production unnoticed by all, and one such category of bugs is called "Runtime Exceptions".
Runtime exceptions are literally called human errors! Something that is the responsibility of the developer to take care of while designing and writing code.
Let's take a simple real-world example.
public class Calculator {
public static void main(String[] args) {
Calculator calculator = new Calculator();
double result1 = calculator.addNumbers(10, 11.2);
System.out.println("Result: " + result1);
double result2 = calculator.addNumbers("10", 11.2);
System.out.println("Result: " + result2);
}
public double addNumbers(Object num1, Object num2) {
double no1 = (double) num1;
double no2 = (double) num2;
return no1 + no2;
}
}
The above Java code illustrates the concept of runtime exceptions. The Calculator class. The method addNumbers(Object num1, Object num2) is designed to work with all kinds of data types.
result1 attempts to add the numbers 10 and 11.2, which is a valid operation. However, result2 tries to add the string "10" and the number 11.2. This action leads to a ClassCastException, a runtime exception.
The issue arises when the code tries to cast the string to a double, which is not allowed, resulting in a runtime error.
This code demonstrates the significance of handling data types correctly in software development to avoid runtime exceptions. Even with thorough testing and development practices, errors like this can occur if data types are not carefully managed.
Some bugs are easy to spot because they cause issues during compilation. We call them 'compile-time bugs or errors.' When you write Java code using tools like Eclipse, IntelliJ, or others, these IDEs highlight problems for you. You'll see red flags in your Java files, signaling compilation errors that need fixing before your code can be built successfully.
We can see this when we make the addNumbers method signature as addNumbers(Number num1, Number num2)
How to make our code safe from ClassCastException?
Generics enhance code reliability by ensuring type safety and preventing ClassCastException errors. When implementing Generics in your project framework, developers are compelled to work with specific object types. Non-compliance results in compilation errors, making it quite challenging to introduce runtime exceptions.
Now let's re-write the above code with generics.
As you can see, we get two errors in the IDE when you change the code with Generic type argument T and type parameter as Double. Thus, bugs are detected during compilation and do not end up in production.
Facing issues? Have Questions? Post them here! I am happy to answer!
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
- [Solution] fatal: not a git repository (or any of the parent directories): .git - Git
- Java Multi-line String Example - Java
- Fetch only content-type using cURL Command - cURL
- How to display hidden files in Eclipse (dot prefixed files) - Eclipse
- How to Launch Terminal App in Mac - MacOS
- Emulator: Warning: restoring GLES1 context from snapshot. App may need reloading. - Android-Studio
- How to force re-download Gradle Dependencies - Gradle
- How to check the size of a Docker Container - Docker