Exception Handling Options in Java
Why is exception handling useful?
Exception handling is useful, it allows the program to keep running in the desired flow while an unexpected exception occurs, and gives the option to provide a user-friendly message to tell the user what is going on with the exception. If we do not handle the exception properly, it may cause the program to crash.
Is it more useful to throw a customized exception instead of a general exception? Why/why not?
I think it would be more useful to throw a customized exception instead of a general exception if it provides a benefit to developers and users. Since providing detailed information about the situation that caused the exception allows us or users to better understand what caused the unexpected events, custom exceptions could provide the flexibility to add attributes and methods that are not part of a standard exception in Java.
Do you need to consider performance implications when using “try/catch”?
Generally, we do not need to consider performance implications when using try/catch, unless an exception occurs. However, you need to consider the scope of the code blocks.
Is exception handling the best way to deal with programmatic errors? What are the alternatives?
The exception is not the best way to deal with programming errors since errors are serious runtime environment problems that are almost certainly not recoverable. There are two types of exceptions, checked exceptions and unchecked exceptions.
A checked exception extends the Exception class. Checked exceptions are checked by the compiler and can prevent code from compiling if not handled properly. You should use checked exceptions for all exceptional events that you can anticipate.
An unchecked exception occurs during the runtime of the program that is not checked by the compiler, and it extends RuntimeException. Unchecked exceptions are for internal errors that you can’t anticipate and the application can’t recover from, usually occurring due to bad programming.
To avoid common unchecked exceptions such as what if the String is null, what if the String is empty, what if the string is not numeric format when parsing it to an integer, etc. We can use the if statement and/or regular expression to have the argument only run the code if it passes the tests we set ahead. Other alternatives for dealing with programmatic errors could be writing better logical codes to prevent system errors, logging, constantly testing, and being precautious of any errors that may occur in the program.