Interview question
What is the difference between throw and throws in Java? Java में throw और throws में क्या अंतर है?
Answer
| Keyword | Used for | Location | Number allowed |
|---|---|---|---|
| throw | Actually throwing an exception instance | Inside a method body | One exception object per throw statement |
| throws | Declaring that a method MIGHT throw an exception | In the method signature | Multiple exceptions, comma-separated |
import java.io.IOException;
import java.sql.SQLException;
// 'throws' - declares possible exceptions in the method signature
public void processFile(String path) throws IOException, SQLException {
if (path == null) {
// 'throw' - actually creates and throws an exception instance
throw new IllegalArgumentException('Path cannot be null');
}
// ... code that might throw IOException or SQLException ...
}
// Caller must handle or re-declare the checked exceptions
public void caller() {
try {
processFile('data.txt');
} catch (IOException | SQLException e) { // multi-catch (Java 7+)
System.out.println('Error: ' + e.getMessage());
}
}
// 'throw' can also re-throw a caught exception
public void handleAndRethrow() throws IOException {
try {
processFile(null);
} catch (IOException e) {
System.out.println('Logging error before rethrow');
throw e; // re-throws the SAME exception object
} catch (SQLException e) {
// handled, not rethrown
}
}
// Memory tip: 'throw' is a VERB (the action of throwing),
// 'throws' is a DECLARATION (a warning label on the method)| Keyword | किसके लिए | कहां | संख्या |
|---|---|---|---|
| throw | Exception instance actually throw करना | Method body के अंदर | एक exception per statement |
| throws | Method शायद exception throw करे बताना | Method signature में | Multiple, comma-separated |
import java.io.IOException;
import java.sql.SQLException;
public void processFile(String path) throws IOException, SQLException {
if (path == null) {
throw new IllegalArgumentException('Path null नहीं हो सकता');
}
}
public void caller() {
try {
processFile('data.txt');
} catch (IOException | SQLException e) {
System.out.println('Error: ' + e.getMessage());
}
}
public void handleAndRethrow() throws IOException {
try {
processFile(null);
} catch (IOException e) {
System.out.println('Rethrow से पहले log करना');
throw e;
} catch (SQLException e) {
// handled, rethrow नहीं
}
}Was this answer clear?