Home » Posts filed under basics
How to avoid NullPointerException
June 29, 2021 Ravi Yasas
java.lang.NullPointerException
When can it be thrown?
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
How to avoid it?
- Use Optional in Java 8
- Call equals() and equalsIgnoreCase() methods on known objects.
- Use valueOf() over toString()
- Use null-safe methods and libraries. Ex: Apache Commons StringUtils.
- Use @NotNull and @Nullable annotations
- Always check for nulls.
basics / beginners / exceptions / java / java8 / nullpointer / optional / toString() / tutorials / value)f()
Throw vs throws in exception handling
June 26, 2021 Ravi Yasas
Throw vs throws
Throw | Throws |
Uses inside a method when it is required to throw an exception | This is used in the method signature in which methods that exceptions can occur. |
Only one exception can be thrown | Throws can be used to declare multiple exceptions |
Used to handle unchecked exceptions | Used to handle checked exceptions |
Usually used to handle custom exceptions | Throws means, it says this method can be thrown these exceptions, when you use this method, you need to handle it. |
basics / beginners / exception handling / exceptions / java / learning / throw / throws / tutorial