0

Sometimes when the JDK declares a method, e.g. Integer.parseInt(String s) it throws a NumberFormatException, yet when the method is called you do not need a try and catch, how can I do this in my own code?

felixk
  • 21
  • 7

5 Answers5

2

It is little unclear what exactly you are asking about - unchecked exceptions or how to avoiding try-catch-finalize blocks.


Unchecked Exceptions

If you are interested in how a method can throw exception, without declaring throwing it (right before body), then beware, that Java programming language does not require methods to catch or to specify unchecked exceptions ("RuntimeException", "Error", and their subclasses).

In contrast, you always have to handle (or declare to throw) all the other types of exceptions.


Avoiding try-catch-finalize

If, however, you're questioning how to avoid try-catch-finalize blocks, then you may throw an exception to the caller, by declaring your method throwing it, as:

[access-modifier] return-type methodName() throws Exception {
    ...
};
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
2

Use the "throws" clause after method declaration. Eg: public static void main(String[] args) throws IOException { }

0

There are basically two kinds of exceptions. Checked and unckecked in Java. All exceptions derived from RuntimeException are unckecked and you don't have to catch these.

So if you create an own exception which extends RuntimeException you don't have to catch it. Also check the already existing ones as they often already fit your needs. Like IllegalStateException or IllegalArgumentException.

olz
  • 116
  • 1
  • 3
0
  1. 1)To create your own exceptions in Java, you need to extend the class you want to create from the Exception class in Java. 2)Then, you can throw your own exceptions by using the throw keyword where you want to write the error you want to show by override its constructor or the getMessage method from the Exception class in the class you created. 3)If you don't want your own exceptions to be try and catch, you need to extend it from the RuntimeException class.
justdoit
  • 47
  • 1
  • 8
0

This exceptions that don't need try_catch are extend from RuntimeException insted of Exception class.

You can create your own RuntimeException like this:

public class CustomException extends RuntimeException {

    public CustomException(String msg) {
        super(msg);
    }

}

Here I leave you a link with more information about diferent exceptions and how to handle them: https://howtodoinjava.com/java/exception-handling/checked-vs-unchecked-exceptions-in-java/