Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the difference between throw and throws in Java? Java में throw और throws में क्या अंतर है?

Answer
KeywordUsed forLocationNumber allowed
throwActually throwing an exception instanceInside a method bodyOne exception object per throw statement
throwsDeclaring that a method MIGHT throw an exceptionIn the method signatureMultiple 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किसके लिएकहांसंख्या
throwException instance actually throw करनाMethod body के अंदरएक exception per statement
throwsMethod शायद 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?