The throws keyword in Java is a method-signature declaration that tells the compiler a method may produce one or more checked exceptions. It does not throw anything itself. The calling code must either handle those exceptions with a try-catch block or declare them onward. Kotlin removes this requirement entirely, treating all exceptions as unchecked.
- throws (Java) declares which checked exceptions a method can propagate; it goes in the method signature.
- throw (Java and Kotlin) is the statement that actually triggers an exception at runtime.
- Kotlin drops checked exceptions entirely, so you never write
throwsin Kotlin source code. - In Kotlin,
tryis an expression, meaning it returns a value you can assign to a variable. - Understanding this distinction matters in interviews, in Android development and in any JVM project that mixes Java and Kotlin code.
Exceptions in the JVM World
Both Java and Kotlin run on the Java Virtual Machine, so they share the same underlying exception hierarchy. Every exception ultimately extends java.lang.Throwable, which splits into Error and Exception. Errors like OutOfMemoryError are JVM-level problems you generally cannot recover from. Exceptions are what your application code deals with day to day.
Checked vs Unchecked Exceptions
This split is the single most important concept before you can understand the throws keyword in Java. A checked exception is one the Java compiler forces you to handle or declare. A classic example is IOException, which you encounter the moment you try to read a file. If you do not wrap it in a try-catch or declare it with throws, your code will not compile.
Unchecked exceptions extend RuntimeException. Think NullPointerException, ArrayIndexOutOfBoundsException or IllegalArgumentException. The compiler does not force you to handle these. They represent programming mistakes, and Java’s designers felt it would be too noisy to require declarations for every possible bug. You can read more about the most common ones in our guide to Java exceptions and common runtime errors.
| Type | Extends | Compiler enforced? | Common examples |
|---|---|---|---|
| Checked exception | Exception |
Yes | IOException, SQLException, ClassNotFoundException |
| Unchecked exception | RuntimeException |
No | NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException |
| Error | Error |
No | OutOfMemoryError, StackOverflowError |
According to the Stack Overflow Developer Survey 2024, Java remains one of the top five most-used programming languages globally, and Kotlin consistently ranks in the top 20. According to the JetBrains State of Developer Ecosystem 2023, 67% of Kotlin developers use it for Android development, where exception handling patterns directly affect app stability. According to the TIOBE Index (April 2024), Java holds a top-five position with an 8.88% rating globally, making exception handling one of the most frequently tested topics in Java technical interviews at companies including TCS, Infosys and Wipro.
In India, exception handling with the throws keyword in Java is a standard topic in the GATE CS syllabus and appears regularly in campus placement assessments such as TCS NQT, Infosys InfyTQ and Wipro NLTH. Universities including Anna University, VTU and JNTU include Java exception handling as a core subject in their B.Tech and MCA programmes.
throws keyword in Java: How It Works
The throws keyword in Java is a declaration in a method signature. It tells the compiler and any developer reading your code that this method may produce a specific exception and that the caller must deal with it. You can list multiple exceptions separated by commas.
Here is the pattern: public void readFile(String path) throws IOException. Any method that calls readFile() must either wrap the call in a try-catch block or itself declare throws IOException in its own signature, passing the responsibility further up the call stack.
A practical mistake that appears constantly in code reviews: developers declare throws Exception on every method just to silence the compiler. That is lazy and genuinely harmful. It forces every caller to handle a completely vague exception type and swallows all context about what actually went wrong. Be specific. Declare exactly the checked exceptions your method can produce, nothing more.
throws keyword in Java Example
// Java: using throws keyword in Java method signature
public void readFile(String path) throws IOException {
FileReader reader = new FileReader(path); // may throw IOException
// read file contents
}
// Caller must handle or re-declare
public void loadConfig() throws IOException {
readFile("/etc/config.properties");
}
// Or handle it directly
public void loadConfigSafe() {
try {
readFile("/etc/config.properties");
} catch (IOException e) {
System.out.println("File not found: " + e.getMessage());
}
}
Difference Between throw and throws in Java
This is where most beginners get tangled, and it costs marks in GATE exams and interview rounds. The two keywords look similar but do completely different jobs.
throw is the action. It is a statement that instantiates an exception object and hands it to the JVM immediately. You write throw new IllegalArgumentException("Age cannot be negative"); inside a method body. The program stops executing the current method and starts unwinding the call stack looking for a handler.
| Feature | throw | throws |
|---|---|---|
| What it is | A statement | A keyword in a method signature |
| Where it goes | Inside the method body | After the method parameter list |
| What it does | Actually throws the exception object | Declares that the method might throw it |
| How many exceptions | One at a time | Multiple, comma-separated |
| Works with unchecked? | Yes | Yes, but pointless for unchecked |
If you are building a career in full stack development or software engineering, clean exception handling is one of those skills that separates junior developers from mid-level ones in code reviews.
try-catch in Kotlin
Kotlin made a deliberate design decision: it has no checked exceptions. The Kotlin designers at JetBrains studied large Java codebases and concluded that checked exceptions often produce boilerplate without meaningfully improving reliability. The official Kotlin documentation states this explicitly. You can throw and catch exceptions in Kotlin, but the compiler never forces you to.
Basic try-catch Syntax in Kotlin
The structure will feel familiar if you know Java. You write a try block, one or more catch blocks for specific exception types, and an optional finally block that always runs. The difference is that none of it is mandatory from the compiler’s perspective.
A realistic Android example: you are parsing a user-entered age from a text field. The user types “twenty” instead of “20”. In Kotlin, you would wrap toInt() in a try block and catch NumberFormatException, then show a Snackbar with a friendly error message. The app does not crash. The user gets feedback. That is the job.
try as an Expression in Kotlin
This is genuinely useful and it is something Java cannot do. In Kotlin, try is an expression, which means the entire block evaluates to a value. You can write val result = try { someRiskyOperation() } catch (e: Exception) { defaultValue } and result gets either the successful return value or your fallback. No null checks, no separate variable declarations, no extra if-else branching.
The value of the try expression is the last expression in the try block, or the last expression in the matching catch block. The finally block does not contribute to the return value; it just runs for cleanup.
runCatching: The Functional Alternative
Kotlin’s standard library includes runCatching { }, which wraps your code in a Result type. On success, you get Result.success(value). On failure, you get Result.failure(exception). You can then chain .getOrElse { } or .onFailure { } without a traditional try-catch block at all. This pattern fits well in functional-style Kotlin code and is increasingly common in Kotlin Multiplatform projects.
Interoperability: Calling Java throws from Kotlin
When you call a Java method that declares throws IOException from Kotlin, the compiler does not force you to handle it. You can, and in most cases you should, but it is your choice. If you are writing a Kotlin function that will be called from Java, annotate it with @Throws(IOException::class) to generate the correct throws declaration in the bytecode so Java callers get the compiler warning they expect. This matters a great deal in mixed-language Android and backend projects.
// Kotlin: @Throws annotation for Java interoperability
@Throws(IOException::class)
fun readFile(path: String): String {
return java.io.File(path).readText()
}
Strong fundamentals like these are exactly what you need if you are exploring BSc Computer Science subjects and their career scope, or planning your path through an MCA programme toward a software development career.
Best Practices for Exception Handling
Knowing the syntax is step one. Using exceptions well is what distinguishes production-quality code from tutorial code. These rules apply whether you are writing Java, Kotlin or a mix of both.
Catch the Most Specific Exception First
If you have multiple catch blocks, put the most specific exception type at the top. Java will throw a compile error if you put a broader type above a narrower one, because the narrower one would be unreachable. Kotlin will not always warn you, so it is on you to get the order right.
Do Not Swallow Exceptions Silently
An empty catch block is one of the most common and damaging mistakes in real codebases. If you catch an exception and do nothing, you have hidden a failure. The application carries on in a broken state and the debugging session that follows is painful. At minimum, log the exception. In production systems, you would typically log it, report it to a monitoring tool like Sentry or Firebase Crashlytics, and either recover or fail fast with a clear message.
Use finally for Resource Cleanup
The finally block runs whether the try block succeeded or threw an exception. It is the right place to close database connections, file streams or network sockets. In modern Java (7+), you would use try-with-resources instead. In Kotlin, the use { } extension function on Closeable does the same job more cleanly.
Do Not Use Exceptions for Flow Control
Throwing and catching exceptions is expensive relative to a simple if-else check. If you are validating that a user’s input is a valid integer, check it with a conditional first rather than letting parseInt() throw and catching the result. Exceptions are for exceptional situations, not routine branching. This is a point that comes up in technical interviews at product companies and it signals that you understand performance trade-offs.
These same disciplined coding habits are foundational when you move into security-focused roles. Insecure exception handling is a real attack surface. Unhandled exceptions that expose stack traces hand an attacker a map of your application internals. If you are curious about the intersection of secure coding and ethical hacking, the CEH v13 AI course at 3.0 University covers exactly this kind of vulnerability in depth.
Getting comfortable with how different languages handle errors also makes you a better developer overall. If you have ever worked through writing and compiling a C program, you will know that C has no exception mechanism at all, which puts the entire burden of error checking on return values. Java’s checked exceptions were a reaction to that problem. Kotlin’s approach is a refinement of Java’s answer. Each generation learns from the last.
The right software development tools also make exception handling easier to practice. An IDE like IntelliJ IDEA highlights unhandled checked exceptions in Java in real time and offers quick fixes, so you can learn the pattern interactively rather than just reading about it.
The core point: the throws keyword in Java is a compile-time contract, not a runtime action, and Kotlin deliberately removes that contract while keeping the ability to throw and catch exceptions at runtime. Master both, understand why they differ, and you will handle this topic confidently in any JVM project or technical interview.
- Write a Java method that reads a file and correctly uses the throws keyword in Java in the signature, then call it from a main method with a proper try-catch block.
- Rewrite the same logic in Kotlin using
tryas an expression that returns a default string if the file read fails. - Explore 3.0 University’s full catalogue of online certification courses to find your next structured learning step in programming, cybersecurity or AI.
Frequently Asked Questions
What is the throws keyword in Java?
The throws keyword in Java is placed in a method’s signature to declare that the method might produce one or more checked exceptions. It does not throw anything itself; it tells the compiler and the calling code that they must handle or further declare those exceptions. Example: public void connect() throws IOException, SQLException.
How does try-catch work in Kotlin?
In Kotlin, a try block contains code that might throw an exception, and one or more catch blocks handle specific exception types if they occur. An optional finally block runs regardless of outcome. Unlike Java, the compiler never forces you to write a try-catch in Kotlin, even for exceptions that would be checked in Java.
Does Kotlin have checked exceptions?
No. Kotlin has no checked exceptions. The language designers at JetBrains made this choice deliberately, citing evidence from large Java codebases that checked exceptions often produced boilerplate without improving code reliability. You can still catch any exception in Kotlin; the compiler just does not require it.
What is the difference between throw and throws in Java?
throw is a statement inside a method body that creates and fires an exception object right now. throws is a keyword in a method signature that declares which checked exceptions the method might produce. One is the action; the other is the warning label. Both exist in Java; only throw exists in Kotlin.
Is try an expression in Kotlin?
Yes. In Kotlin, try is an expression, meaning the entire try-catch block evaluates to a value. You can write val result = try { riskyCall() } catch (e: Exception) { fallbackValue } and assign the outcome directly to a variable. The value comes from the last expression in whichever block executes. Java does not support this.
Can you use the throws keyword in Java with unchecked exceptions?
Yes, you can declare unchecked exceptions with throws in Java, but it is not required and generally not recommended. The compiler does not enforce handling of unchecked exceptions regardless of whether they appear in a throws declaration. Reserve the throws keyword in Java for checked exceptions where you want to make the contract explicit to callers.
Last updated: June 2025. Reviewed by the 3University editorial team.